/** * Tests using entity fields of the field field type. */ public function testShapeItem() { // Verify entity creation. $entity = EntityTest::create(); $shape = 'cube'; $color = 'blue'; $entity->{$this->fieldName}->shape = $shape; $entity->{$this->fieldName}->color = $color; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertTrue($entity->{$this->fieldName} instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->{$this->fieldName}[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->{$this->fieldName}->shape, $shape); $this->assertEqual($entity->{$this->fieldName}->color, $color); $this->assertEqual($entity->{$this->fieldName}[0]->shape, $shape); $this->assertEqual($entity->{$this->fieldName}[0]->color, $color); // Verify changing the field value. $new_shape = 'circle'; $new_color = 'red'; $entity->{$this->fieldName}->shape = $new_shape; $entity->{$this->fieldName}->color = $new_color; $this->assertEqual($entity->{$this->fieldName}->shape, $new_shape); $this->assertEqual($entity->{$this->fieldName}->color, $new_color); // Read changed entity and assert changed values. $entity->save(); $entity = EntityTest::load($id); $this->assertEqual($entity->{$this->fieldName}->shape, $new_shape); $this->assertEqual($entity->{$this->fieldName}->color, $new_color); }
/** * Tests using entity fields of the field field type. */ public function testTestItem() { // Verify entity creation. $entity = EntityTest::create(); $value = rand(1, 10); $entity->field_test = $value; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertTrue($entity->{$this->fieldName} instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->{$this->fieldName}[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->{$this->fieldName}->value, $value); $this->assertEqual($entity->{$this->fieldName}[0]->value, $value); // Verify changing the field value. $new_value = rand(1, 10); $entity->field_test->value = $new_value; $this->assertEqual($entity->{$this->fieldName}->value, $new_value); // Read changed entity and assert changed values. $entity->save(); $entity = EntityTest::load($id); $this->assertEqual($entity->{$this->fieldName}->value, $new_value); // Test the schema for this field type. $expected_schema = array('columns' => array('value' => array('type' => 'int', 'size' => 'medium')), 'unique keys' => array(), 'indexes' => array('value' => array('value')), 'foreign keys' => array()); $field_schema = BaseFieldDefinition::create('test_field')->getSchema(); $this->assertEqual($field_schema, $expected_schema); }
/** * Tests using entity fields of the boolean field type. */ public function testBooleanItem() { // Verify entity creation. $entity = EntityTest::create(); $value = '1'; $entity->field_boolean = $value; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertTrue($entity->field_boolean instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_boolean[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_boolean->value, $value); $this->assertEqual($entity->field_boolean[0]->value, $value); // Verify changing the boolean value. $new_value = 0; $entity->field_boolean->value = $new_value; $this->assertEqual($entity->field_boolean->value, $new_value); // Read changed entity and assert changed values. $entity->save(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_boolean->value, $new_value); // Test sample item generation. $entity = EntityTest::create(); $entity->field_boolean->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * Helper function for testTextfieldWidgets(). */ function _testTextfieldWidgets($field_type, $widget_type) { // Create a field. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $field_type)); $field_storage->save(); FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label'])->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => $widget_type, 'settings' => array('placeholder' => 'A placeholder on ' . $widget_type)))->save(); entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name)->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoFieldByName("{$field_name}[0][format]", '1', 'Format selector is not displayed'); $this->assertRaw(format_string('placeholder="A placeholder on @widget_type"', array('@widget_type' => $widget_type))); // Submit with some value. $value = $this->randomMachineName(); $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created'); // Display the entity. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent(\Drupal::service('renderer')->renderRoot($content)); $this->assertText($value, 'Filtered tags are not displayed'); }
/** * Tests email field. */ function testEmailField() { // Create a field with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); $this->fieldStorage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'email')); $this->fieldStorage->save(); $this->field = FieldConfig::create(['field_storage' => $this->fieldStorage, 'bundle' => 'entity_test']); $this->field->save(); // Create a form display for the default form mode. entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => 'email_default', 'settings' => array('placeholder' => '*****@*****.**')))->save(); // Create a display for the full view mode. entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name, array('type' => 'email_mailto'))->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget found.'); $this->assertRaw('placeholder="*****@*****.**"'); // Submit a valid email address and ensure it is accepted. $value = '*****@*****.**'; $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); $this->assertRaw($value); // Verify that a mailto link is displayed. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent(\Drupal::service('renderer')->renderRoot($content)); $this->assertLinkByHref('mailto:test@example.com'); }
/** * Tests loading entities created in a batch in simpletest_test_install(). */ public function testLoadingEntitiesCreatedInBatch() { $entity1 = EntityTest::load(1); $this->assertNotNull($entity1, 'Successfully loaded entity 1.'); $entity2 = EntityTest::load(2); $this->assertNotNull($entity2, 'Successfully loaded entity 2.'); }
/** * Tests deleting field storages and fields as part of config import. */ public function testImportDeleteUninstall() { // Create a telephone field. $field_storage = FieldStorageConfig::create(array('field_name' => 'field_tel', 'entity_type' => 'entity_test', 'type' => 'telephone')); $field_storage->save(); FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test'])->save(); // Create a text field. $date_field_storage = FieldStorageConfig::create(array('field_name' => 'field_date', 'entity_type' => 'entity_test', 'type' => 'datetime')); $date_field_storage->save(); FieldConfig::create(['field_storage' => $date_field_storage, 'bundle' => 'entity_test'])->save(); // Create an entity which has values for the telephone and text field. $entity = EntityTest::create(); $value = '+0123456789'; $entity->field_tel = $value; $entity->field_date = time(); $entity->name->value = $this->randomMachineName(); $entity->save(); // Delete the text field before exporting configuration so that we can test // that deleted fields that are provided by modules that will be uninstalled // are also purged and that the UI message includes such fields. $date_field_storage->delete(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_tel->value, $value); $this->assertEqual($entity->field_tel[0]->value, $value); $active = $this->container->get('config.storage'); $sync = $this->container->get('config.storage.sync'); $this->copyConfig($active, $sync); // Stage uninstall of the Telephone module. $core_extension = $this->config('core.extension')->get(); unset($core_extension['module']['telephone']); $sync->write('core.extension', $core_extension); // Stage the field deletion $sync->delete('field.storage.entity_test.field_tel'); $sync->delete('field.field.entity_test.entity_test.field_tel'); $this->drupalGet('admin/config/development/configuration'); // Test that the message for one field being purged during a configuration // synchronization is correct. $this->assertText('This synchronization will delete data from the field entity_test.field_tel.'); // Stage an uninstall of the datetime module to test the message for // multiple fields. unset($core_extension['module']['datetime']); $sync->write('core.extension', $core_extension); $this->drupalGet('admin/config/development/configuration'); $this->assertText('This synchronization will delete data from the fields: entity_test.field_tel, entity_test.field_date.'); // This will purge all the data, delete the field and uninstall the // Telephone and Text modules. $this->drupalPostForm(NULL, array(), t('Import all')); $this->assertNoText('Field data will be deleted by this synchronization.'); $this->rebuildContainer(); $this->assertFalse(\Drupal::moduleHandler()->moduleExists('telephone')); $this->assertFalse(\Drupal::entityManager()->loadEntityByUuid('field_storage_config', $field_storage->uuid()), 'The telephone field has been deleted by the configuration synchronization'); $deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array(); $this->assertFalse(isset($deleted_storages[$field_storage->uuid()]), 'Telephone field has been completed removed from the system.'); $this->assertFalse(isset($deleted_storages[$field_storage->uuid()]), 'Text field has been completed removed from the system.'); }
/** * Tests using entity fields of the file field type. */ public function testFileItem() { // Check that the selection handler was automatically assigned to // 'default:file'. $field_definition = FieldConfig::load('entity_test.entity_test.file_test'); $handler_id = $field_definition->getSetting('handler'); $this->assertEqual($handler_id, 'default:file'); // Create a test entity with the $entity = EntityTest::create(); $entity->file_test->target_id = $this->file->id(); $entity->file_test->display = 1; $entity->file_test->description = $description = $this->randomMachineName(); $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = EntityTest::load($entity->id()); $this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->file_test->target_id, $this->file->id()); $this->assertEqual($entity->file_test->display, 1); $this->assertEqual($entity->file_test->description, $description); $this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri()); $this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri())); $this->assertEqual($entity->file_test->entity->id(), $this->file->id()); $this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid()); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-2.txt', $this->randomMachineName()); $file2 = File::create(['uri' => 'public://example-2.txt']); $file2->save(); $entity->file_test->target_id = $file2->id(); $this->assertEqual($entity->file_test->entity->id(), $file2->id()); $this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri()); // Test the deletion of an entity having an entity reference field targeting // a non-existing entity. $file2->delete(); $entity->delete(); // Test the generateSampleValue() method. $entity = EntityTest::create(); $entity->file_test->generateSampleItems(); $this->entityValidateAndSave($entity); // Verify that the sample file was stored in the correct directory. $uri = $entity->file_test->entity->getFileUri(); $this->assertEqual($this->directory, dirname(file_uri_target($uri))); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-3.txt', $this->randomMachineName()); // Test unsaved file entity. $file3 = File::create(['uri' => 'public://example-3.txt']); $display = entity_get_display('entity_test', 'entity_test', 'default'); $display->setComponent('file_test', ['label' => 'above', 'type' => 'file_default', 'weight' => 1])->save(); $entity = EntityTest::create(); $entity->file_test = array('entity' => $file3); $uri = $file3->getFileUri(); $output = entity_view($entity, 'default'); \Drupal::service('renderer')->renderRoot($output); $this->assertTrue(!empty($entity->file_test->entity)); $this->assertEqual($entity->file_test->entity->getFileUri(), $uri); }
/** * Tests using entity fields of the number field type. */ public function testNumberItem() { // Verify entity creation. $entity = EntityTest::create(); $integer = rand(0, 10); $entity->field_integer = $integer; $float = 3.14; $entity->field_float = $float; $entity->field_decimal = '20-40'; $violations = $entity->validate(); $this->assertIdentical(1, count($violations), 'Wrong decimal value causes validation error'); $decimal = '31.3'; $entity->field_decimal = $decimal; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertTrue($entity->field_integer instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_integer[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_integer->value, $integer); $this->assertEqual($entity->field_integer[0]->value, $integer); $this->assertTrue($entity->field_float instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_float[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_float->value, $float); $this->assertEqual($entity->field_float[0]->value, $float); $this->assertTrue($entity->field_decimal instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_decimal[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_decimal->value, $decimal); $this->assertEqual($entity->field_decimal[0]->value, $decimal); // Verify changing the number value. $new_integer = rand(11, 20); $new_float = rand(1001, 2000) / 100; $new_decimal = '18.2'; $entity->field_integer->value = $new_integer; $this->assertEqual($entity->field_integer->value, $new_integer); $entity->field_float->value = $new_float; $this->assertEqual($entity->field_float->value, $new_float); $entity->field_decimal->value = $new_decimal; $this->assertEqual($entity->field_decimal->value, $new_decimal); // Read changed entity and assert changed values. $entity->save(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_integer->value, $new_integer); $this->assertEqual($entity->field_float->value, $new_float); $this->assertEqual($entity->field_decimal->value, $new_decimal); /// Test sample item generation. $entity = EntityTest::create(); $entity->field_integer->generateSampleItems(); $entity->field_float->generateSampleItems(); $entity->field_decimal->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * Tests using entity fields of the image field type. */ public function testImageItem() { // Create a test entity with the image field set. $entity = EntityTest::create(); $entity->image_test->target_id = $this->image->id(); $entity->image_test->alt = $alt = $this->randomMachineName(); $entity->image_test->title = $title = $this->randomMachineName(); $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = EntityTest::load($entity->id()); $this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->image_test->target_id, $this->image->id()); $this->assertEqual($entity->image_test->alt, $alt); $this->assertEqual($entity->image_test->title, $title); $image = $this->imageFactory->get('public://example.jpg'); $this->assertEqual($entity->image_test->width, $image->getWidth()); $this->assertEqual($entity->image_test->height, $image->getHeight()); $this->assertEqual($entity->image_test->entity->id(), $this->image->id()); $this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid()); // Make sure the computed entity reflects updates to the referenced file. file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example-2.jpg'); $image2 = File::create(['uri' => 'public://example-2.jpg']); $image2->save(); $entity->image_test->target_id = $image2->id(); $entity->image_test->alt = $new_alt = $this->randomMachineName(); // The width and height is only updated when width is not set. $entity->image_test->width = NULL; $entity->save(); $this->assertEqual($entity->image_test->entity->id(), $image2->id()); $this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri()); $image = $this->imageFactory->get('public://example-2.jpg'); $this->assertEqual($entity->image_test->width, $image->getWidth()); $this->assertEqual($entity->image_test->height, $image->getHeight()); $this->assertEqual($entity->image_test->alt, $new_alt); // Check that the image item can be set to the referenced file directly. $entity->image_test = $this->image; $this->assertEqual($entity->image_test->target_id, $this->image->id()); // Delete the image and try to save the entity again. $this->image->delete(); $entity = EntityTest::create(array('mame' => $this->randomMachineName())); $entity->save(); // Test image item properties. $expected = array('target_id', 'entity', 'alt', 'title', 'width', 'height'); $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions(); $this->assertEqual(array_keys($properties), $expected); // Test the generateSampleValue() method. $entity = EntityTest::create(); $entity->image_test->generateSampleItems(); $this->entityValidateAndSave($entity); $this->assertEqual($entity->image_test->entity->get('filemime')->value, 'image/jpeg'); }
/** * Helper function for testTextfieldWidgetsFormatted(). */ function _testTextfieldWidgetsFormatted($field_type, $widget_type) { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); // Create a field. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $field_type)); $field_storage->save(); FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label'])->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => $widget_type))->save(); entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name)->save(); // Disable all text formats besides the plain text fallback format. $this->drupalLogin($this->adminUser); foreach (filter_formats() as $format) { if (!$format->isFallbackFormat()) { $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', array(), t('Disable')); } } $this->drupalLogin($this->webUser); // Display the creation form. Since the user only has access to one format, // no format selector will be displayed. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoFieldByName("{$field_name}[0][format]", '', 'Format selector is not displayed'); // Submit with data that should be filtered. $value = '<em>' . $this->randomMachineName() . '</em>'; $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created'); // Display the entity. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent($renderer->renderRoot($content)); $this->assertNoRaw($value, 'HTML tags are not displayed.'); $this->assertEscaped($value, 'Escaped HTML is displayed correctly.'); // Create a new text format that does not escape HTML, and grant the user // access to it. $this->drupalLogin($this->adminUser); $edit = array('format' => Unicode::strtolower($this->randomMachineName()), 'name' => $this->randomMachineName()); $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration')); filter_formats_reset(); $format = FilterFormat::load($edit['format']); $format_id = $format->id(); $permission = $format->getPermissionName(); $roles = $this->webUser->getRoles(); $rid = $roles[0]; user_role_grant_permissions($rid, array($permission)); $this->drupalLogin($this->webUser); // Display edition form. // We should now have a 'text format' selector. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName("{$field_name}[0][value]", NULL, 'Widget is displayed'); $this->assertFieldByName("{$field_name}[0][format]", NULL, 'Format selector is displayed'); // Edit and change the text format to the new one that was created. $edit = array("{$field_name}[0][format]" => $format_id); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated'); // Display the entity. $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id)); $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent($renderer->renderRoot($content)); $this->assertRaw($value, 'Value is displayed unfiltered'); }
/** * Renders a test_entity and sets the output in the internal browser. * * @param int $id * The test_entity ID to render. * @param string $view_mode * (optional) The view mode to use for rendering. * @param bool $reset * (optional) Whether to reset the entity_test storage cache. Defaults to * TRUE to simplify testing. */ protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) { if ($reset) { $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id)); } $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), $view_mode); $content = $display->build($entity); $output = \Drupal::service('renderer')->renderRoot($content); $this->setRawContent($output); $this->verbose($output); }
/** * Tests purging already deleted field storages and fields during a config * import. */ public function testImportAlreadyDeletedUninstall() { // Create a telephone field for validation. $field_storage = FieldStorageConfig::create(array('field_name' => 'field_test', 'entity_type' => 'entity_test', 'type' => 'telephone')); $field_storage->save(); $field_storage_uuid = $field_storage->uuid(); FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test'])->save(); // Create 12 entities to ensure that the purging works as expected. for ($i = 0; $i < 12; $i++) { $entity = EntityTest::create(); $value = '+0123456789'; $entity->field_test = $value; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_test->value, $value); } // Delete the field. $field_storage->delete(); $active = $this->container->get('config.storage'); $sync = $this->container->get('config.storage.sync'); $this->copyConfig($active, $sync); // Stage uninstall of the Telephone module. $core_extension = $this->config('core.extension')->get(); unset($core_extension['module']['telephone']); $sync->write('core.extension', $core_extension); $deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array(); $this->assertTrue(isset($deleted_storages[$field_storage_uuid]), 'Field has been deleted and needs purging before configuration synchronization.'); $steps = $this->configImporter()->initialize(); $this->assertIdentical($steps[0], array('\\Drupal\\field\\ConfigImporterFieldPurger', 'process'), 'The additional process configuration synchronization step has been added.'); // This will purge all the data, delete the field and uninstall the // Telephone module. $this->configImporter()->import(); $this->assertFalse(\Drupal::moduleHandler()->moduleExists('telephone')); $deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array(); $this->assertFalse(isset($deleted_storages[$field_storage_uuid]), 'Field has been completed removed from the system.'); }
/** * Tests the entity reference field type for referencing config entities. */ public function testConfigEntityReferenceItem() { $referenced_entity_id = $this->vocabulary->id(); // Just being able to create the entity like this verifies a lot of code. $entity = EntityTest::create(); $entity->field_test_taxonomy_vocabulary->target_id = $referenced_entity_id; $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = EntityTest::load($entity->id()); $this->assertTrue($entity->field_test_taxonomy_vocabulary instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test_taxonomy_vocabulary[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $this->vocabulary->label()); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $referenced_entity_id); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->uuid(), $this->vocabulary->uuid()); // Change the name of the term via the reference. $new_name = $this->randomMachineName(); $entity->field_test_taxonomy_vocabulary->entity->set('name', $new_name); $entity->field_test_taxonomy_vocabulary->entity->save(); // Verify it is the correct name. $vocabulary = Vocabulary::load($referenced_entity_id); $this->assertEqual($vocabulary->label(), $new_name); // Make sure the computed term reflects updates to the term id. $vocabulary2 = $vocabulary = Vocabulary::create(['name' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $vocabulary2->save(); $entity->field_test_taxonomy_vocabulary->target_id = $vocabulary2->id(); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $vocabulary2->id()); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $vocabulary2->label()); // Delete terms so we have nothing to reference and try again $this->vocabulary->delete(); $vocabulary2->delete(); $entity = EntityTest::create(array('name' => $this->randomMachineName())); $entity->save(); }
/** * Tests GetUntransformedTextCommand AJAX command. */ public function testGetUntransformedTextCommand() { // Create an entity with values for the field. $entity = EntityTest::create(); $entity->{$this->fieldName}->value = 'Test'; $entity->{$this->fieldName}->format = 'full_html'; $entity->save(); $entity = EntityTest::load($entity->id()); // Verify AJAX response. $controller = new EditorController(); $request = new Request(); $response = $controller->getUntransformedText($entity, $this->fieldName, LanguageInterface::LANGCODE_DEFAULT, 'default'); $expected = array(array('command' => 'editorGetUntransformedText', 'data' => 'Test')); $ajax_response_attachments_processor = \Drupal::service('ajax_response.attachments_processor'); $subscriber = new AjaxResponseSubscriber($ajax_response_attachments_processor); $event = new FilterResponseEvent(\Drupal::service('http_kernel'), $request, HttpKernelInterface::MASTER_REQUEST, $response); $subscriber->onResponse($event); $this->assertEqual(Json::encode($expected), $response->getContent(), 'The GetUntransformedTextCommand AJAX command works correctly.'); }
/** * Renders a entity_test and sets the output in the internal browser. * * @param int $id * The entity_test ID to render. * @param string $view_mode * (optional) The view mode to use for rendering. Defaults to 'full'. * @param bool $reset * (optional) Whether to reset the entity_test controller cache. Defaults to * TRUE to simplify testing. */ protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) { if ($reset) { $this->container->get('entity_type.manager')->getStorage('entity_test')->resetCache([$id]); } $entity = EntityTest::load($id); $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode); $build = $display->build($entity); $output = $this->container->get('renderer')->renderRoot($build); $this->setRawContent($output); $this->verbose($output); }
/** * Tests a field whose associated in-place editor generates custom metadata. */ public function testEditorWithCustomMetadata() { $this->editorManager = $this->container->get('plugin.manager.quickedit.editor'); $this->editorSelector = new EditorSelector($this->editorManager, $this->container->get('plugin.manager.field.formatter')); $this->metadataGenerator = new MetadataGenerator($this->accessChecker, $this->editorSelector, $this->editorManager); $this->editorManager = $this->container->get('plugin.manager.quickedit.editor'); $this->editorSelector = new EditorSelector($this->editorManager, $this->container->get('plugin.manager.field.formatter')); $this->metadataGenerator = new MetadataGenerator($this->accessChecker, $this->editorSelector, $this->editorManager); // Create a rich text field. $field_name = 'field_rich'; $field_label = 'Rich text field'; $this->createFieldWithStorage($field_name, 'text', 1, $field_label, array(), 'text_textfield', array('size' => 42), 'text_default', array()); // Create a text format. $full_html_format = FilterFormat::create(array('format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => array('filter_htmlcorrector' => array('status' => 1)))); $full_html_format->save(); // Create an entity with values for this rich text field. $entity = EntityTest::create(); $entity->{$field_name}->value = 'Test'; $entity->{$field_name}->format = 'full_html'; $entity->save(); $entity = EntityTest::load($entity->id()); // Verify metadata. $items = $entity->get($field_name); $metadata = $this->metadataGenerator->generateFieldMetadata($items, 'default'); $expected = array('access' => TRUE, 'label' => 'Rich text field', 'editor' => 'wysiwyg', 'custom' => array('format' => 'full_html')); $this->assertEqual($expected, $metadata); //, 'The correct metadata (including custom metadata) is generated.'); }
/** * Tests setting the value of the DateTimeItem directly. */ public function testSetValueProperty() { // Test Date::setValue(). $entity = EntityTest::create(); $value = '2014-01-01T20:00:00Z'; $entity->set('field_datetime', $value); $entity->save(); // Load the entity and ensure the field was saved correctly. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_datetime[0]->value, $value, '"Value" property can be set directly.'); }
/** * Tests widgets handling multiple values. */ function testFieldFormMultipleWidget() { // Create a field with fixed cardinality, configure the form to use a // "multiple" widget. $field_storage = $this->fieldStorageMultiple; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')->setComponent($field_name, array('type' => 'test_field_widget_multiple'))->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName($field_name, '', 'Widget is displayed.'); // Create entity with three values. $edit = array($field_name => '1, 2, 3'); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; // Check that the values were saved. $entity_init = EntityTest::load($id); $this->assertFieldValues($entity_init, $field_name, array(1, 2, 3)); // Display the form, check that the values are correctly filled in. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName($field_name, '1, 2, 3', 'Widget is displayed.'); // Submit the form with more values than the field accepts. $edit = array($field_name => '1, 2, 3, 4, 5'); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.'); // Check that the field values were not submitted. $this->assertFieldValues($entity_init, $field_name, array(1, 2, 3)); }
/** * Tests boolean field. */ function testBooleanField() { $on = $this->randomMachineName(); $off = $this->randomMachineName(); $label = $this->randomMachineName(); // Create a field with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); $this->fieldStorage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'boolean')); $this->fieldStorage->save(); $this->field = FieldConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'bundle' => 'entity_test', 'label' => $label, 'required' => TRUE, 'settings' => array('on_label' => $on, 'off_label' => $off))); $this->field->save(); // Create a form display for the default form mode. entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => 'boolean_checkbox'))->save(); // Create a display for the full view mode. entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name, array('type' => 'boolean'))->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[value]", '', 'Widget found.'); $this->assertText($this->field->label(), 'Uses field label by default.'); $this->assertNoRaw($on, 'Does not use the "On" label.'); // Submit and ensure it is accepted. $edit = array("{$field_name}[value]" => 1); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); // Verify that boolean value is displayed. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent(\Drupal::service('renderer')->renderRoot($content)); $this->assertRaw('<div class="field__item">' . $on . '</div>'); // Test with "On" label option. entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => 'boolean_checkbox', 'settings' => array('display_label' => FALSE)))->save(); $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[value]", '', 'Widget found.'); $this->assertRaw($on); $this->assertNoText($this->field->label()); // Test if we can change the on label. $on = $this->randomMachineName(); $edit = array('settings[on_label]' => $on); $this->drupalPostForm('entity_test/structure/entity_test/fields/entity_test.entity_test.' . $field_name, $edit, t('Save settings')); // Check if we see the updated labels in the creation form. $this->drupalGet('entity_test/add'); $this->assertRaw($on); // Go to the form display page and check if the default settings works as // expected. $fieldEditUrl = 'entity_test/structure/entity_test/form-display'; $this->drupalGet($fieldEditUrl); // Click on the widget settings button to open the widget settings form. $this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit"); $this->assertText('Use field label instead of the "On label" as label', t('Display setting checkbox available.')); // Enable setting. $edit = array('fields[' . $field_name . '][settings_edit_form][settings][display_label]' => 1); $this->drupalPostAjaxForm(NULL, $edit, $field_name . "_plugin_settings_update"); $this->drupalPostForm(NULL, NULL, 'Save'); // Go again to the form display page and check if the setting // is stored and has the expected effect. $this->drupalGet($fieldEditUrl); $this->assertText('Use field label: Yes', 'Checking the display settings checkbox updated the value.'); $this->drupalPostAjaxForm(NULL, array(), $field_name . "_settings_edit"); $this->assertText('Use field label instead of the "On label" as label', t('Display setting checkbox is available')); $this->assertFieldByXPath('*//input[starts-with(@id, "edit-fields-' . $field_name . '-settings-edit-form-settings-display-label") and @value="1"]', TRUE, t('Display label changes label of the checkbox')); // Test the boolean field settings. $this->drupalGet('entity_test/structure/entity_test/fields/entity_test.entity_test.' . $field_name); $this->assertFieldById('edit-settings-on-label', $on); $this->assertFieldById('edit-settings-off-label', $off); }
/** * @covers ::load * @covers ::getEntityTypeFromStaticClass * * Tests if an assertion is thrown if Entity::load() is called on a class * that matches multiple times. * * @expectedException \Drupal\Core\Entity\Exception\AmbiguousEntityClassException */ public function testLoadWithAmbiguousClasses() { // Use an entity type object which has the methods enabled which are being // called by the protected method Entity::getEntityTypeFromStaticClass(). $methods = get_class_methods('Drupal\\Core\\Entity\\EntityType'); unset($methods[array_search('getClass', $methods)]); unset($methods[array_search('setClass', $methods)]); $first_entity_type = $this->getMockBuilder('\\Drupal\\Core\\Entity\\EntityType')->disableOriginalConstructor()->setMethods($methods)->getMock(); $first_entity_type->setClass('Drupal\\entity_test\\Entity\\EntityTest'); $second_entity_type = $this->getMockBuilder('\\Drupal\\Core\\Entity\\EntityType')->disableOriginalConstructor()->setMethods($methods)->setMockClassName($this->randomMachineName())->getMock(); $second_entity_type->setClass('Drupal\\entity_test\\Entity\\EntityTest'); $this->entityManager->expects($this->once())->method('getDefinitions')->will($this->returnValue(array('entity_test_mul' => $first_entity_type, 'entity_test_mul_rev' => $second_entity_type))); // Call EntityTest::load() statically and check that it throws an exception. EntityTest::load(1); }
/** * Reloads the specified entity. * * @param \Drupal\entity_test\Entity\EntityTest $entity * An entity object. * * @return \Drupal\entity_test\Entity\EntityTest * The reloaded entity object. */ protected function reloadEntity(EntityTest $entity) { $this->entityManager->useCaches(FALSE); $this->entityManager->getStorage('entity_test')->resetCache([$entity->id()]); return EntityTest::load($entity->id()); }
/** * Tests date field functionality. */ public function testDateRangeField() { $field_name = $this->fieldStorage->getName(); // Loop through defined timezones to test that date-only fields work at the // extremes. foreach (static::$timezones as $timezone) { $this->setSiteTimezone($timezone); // Ensure field is set to a date-only field. $this->fieldStorage->setSetting('datetime_type', DateRangeItem::DATETIME_TYPE_DATE); $this->fieldStorage->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element found.'); $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element found.'); $this->assertFieldByXPath('//*[@id="edit-' . $field_name . '-wrapper"]/h4[contains(@class, "js-form-required")]', TRUE, 'Required markup found'); $this->assertNoFieldByName("{$field_name}[0][value][time]", '', 'Start time element not found.'); $this->assertNoFieldByName("{$field_name}[0][end_value][time]", '', 'End time element not found.'); // Build up dates in the UTC timezone. $value = '2012-12-31 00:00:00'; $start_date = new DrupalDateTime($value, 'UTC'); $end_value = '2013-06-06 00:00:00'; $end_date = new DrupalDateTime($end_value, 'UTC'); // Submit a valid date and ensure it is accepted. $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); $edit = array("{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $end_date->format($date_format)); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); $this->assertRaw($start_date->format($date_format)); $this->assertNoRaw($start_date->format($time_format)); $this->assertRaw($end_date->format($date_format)); $this->assertNoRaw($end_date->format($time_format)); // Verify the date doesn't change when entity is edited through the form. $entity = EntityTest::load($id); $this->assertEqual('2012-12-31', $entity->{$field_name}->value); $this->assertEqual('2013-06-06', $entity->{$field_name}->end_value); $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->drupalPostForm(NULL, [], t('Save')); $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->drupalPostForm(NULL, [], t('Save')); $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->drupalPostForm(NULL, [], t('Save')); $entity = EntityTest::load($id); $this->assertEqual('2012-12-31', $entity->{$field_name}->value); $this->assertEqual('2013-06-06', $entity->{$field_name}->end_value); // Formats that display a time component for date-only fields will display // the default time, so that is applied before calculating the expected // value. datetime_date_default_time($start_date); datetime_date_default_time($end_date); // Reset display options since these get changed below. $this->displayOptions = ['type' => 'daterange_default', 'label' => 'hidden', 'settings' => ['format_type' => 'long', 'separator' => 'THESEPARATOR'] + $this->defaultSettings]; // Verify that the default formatter works. entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE); $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\\TH:i:s\\Z', DATETIME_STORAGE_TIMEZONE); $end_expected = $this->dateFormatter->format($end_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE); $end_expected_iso = $this->dateFormatter->format($end_date->getTimestamp(), 'custom', 'Y-m-d\\TH:i:s\\Z', DATETIME_STORAGE_TIMEZONE); $this->renderTestEntity($id); $this->assertFieldByXPath('//time[@datetime="' . $start_expected_iso . '"]', $start_expected, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso])); $this->assertFieldByXPath('//time[@datetime="' . $end_expected_iso . '"]', $end_expected, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $end_expected, '%expected_iso' => $end_expected_iso])); $this->assertText(' THESEPARATOR ', 'Found proper separator'); // Verify that the plain formatter works. $this->displayOptions['type'] = 'daterange_plain'; $this->displayOptions['settings'] = $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT) . ' - ' . $end_date->format(DATETIME_DATE_STORAGE_FORMAT); $this->renderTestEntity($id); $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); // Verify that the custom formatter works. $this->displayOptions['type'] = 'daterange_custom'; $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']) . ' - ' . $end_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); // Test formatters when start date and end date are the same $this->drupalGet('entity_test/add'); $value = '2012-12-31 00:00:00'; $start_date = new DrupalDateTime($value, 'UTC'); $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); $edit = array("{$field_name}[0][value][date]" => $start_date->format($date_format), "{$field_name}[0][end_value][date]" => $start_date->format($date_format)); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); datetime_date_default_time($start_date); $this->displayOptions = ['type' => 'daterange_default', 'label' => 'hidden', 'settings' => ['format_type' => 'long', 'separator' => 'THESEPARATOR'] + $this->defaultSettings]; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $start_expected = $this->dateFormatter->format($start_date->getTimestamp(), 'long', '', DATETIME_STORAGE_TIMEZONE); $start_expected_iso = $this->dateFormatter->format($start_date->getTimestamp(), 'custom', 'Y-m-d\\TH:i:s\\Z', DATETIME_STORAGE_TIMEZONE); $this->renderTestEntity($id); $this->assertFieldByXPath('//time[@datetime="' . $start_expected_iso . '"]', $start_expected, new FormattableMarkup('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', ['%value' => 'long', '%expected' => $start_expected, '%expected_iso' => $start_expected_iso])); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); $this->displayOptions['type'] = 'daterange_plain'; $this->displayOptions['settings'] = $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $start_date->format(DATETIME_DATE_STORAGE_FORMAT); $this->renderTestEntity($id); $this->assertText($expected, new FormattableMarkup('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); $this->displayOptions['type'] = 'daterange_custom'; $this->displayOptions['settings'] = array('date_format' => 'm/d/Y') + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $start_date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); $this->assertText($expected, new FormattableMarkup('Formatted date field using daterange_custom format displayed as %expected.', array('%expected' => $expected))); $this->assertNoText(' THESEPARATOR ', 'Separator not found on page'); } }
/** * Tests the result of a view with complex field configuration. * * A complex field configuration contains multiple times the same field, with * different delta limit / offset. */ public function testFieldAliasRender() { $executable = Views::getView('test_field_alias_test'); $executable->execute(); for ($i = 0; $i < 5; $i++) { $this->assertEqual((string) ($i + 1), $executable->getStyle()->getField($i, 'id')); $this->assertEqual('test ' . $i, $executable->getStyle()->getField($i, 'name')); $entity = EntityTest::load($i + 1); $this->assertEqual('<a href="' . $entity->url() . '" hreflang="' . $entity->language()->getId() . '">test ' . $i . '</a>', (string) $executable->getStyle()->getField($i, 'name_alias')); } }
/** * Tests using entity fields of the link field type. */ public function testLinkItem() { // Create entity. $entity = EntityTest::create(); $url = 'https://www.drupal.org?test_param=test_value'; $parsed_url = UrlHelper::parse($url); $title = $this->randomMachineName(); $class = $this->randomMachineName(); $entity->field_test->uri = $parsed_url['path']; $entity->field_test->title = $title; $entity->field_test->first()->get('options')->set('query', $parsed_url['query']); $entity->field_test->first()->get('options')->set('attributes', array('class' => $class)); $this->assertEquals(['query' => $parsed_url['query'], 'attributes' => ['class' => $class], 'external' => TRUE], $entity->field_test->first()->getUrl()->getOptions()); $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify that the field value is changed. $id = $entity->id(); $entity = EntityTest::load($id); $this->assertTrue($entity->field_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test->uri, $parsed_url['path']); $this->assertEqual($entity->field_test[0]->uri, $parsed_url['path']); $this->assertEqual($entity->field_test->title, $title); $this->assertEqual($entity->field_test[0]->title, $title); $this->assertEqual($entity->field_test->options['attributes']['class'], $class); $this->assertEqual($entity->field_test->options['query'], $parsed_url['query']); // Update only the entity name property to check if the link field data will // remain intact. $entity->name->value = $this->randomMachineName(); $entity->save(); $id = $entity->id(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_test->uri, $parsed_url['path']); $this->assertEqual($entity->field_test->options['attributes']['class'], $class); $this->assertEqual($entity->field_test->options['query'], $parsed_url['query']); // Verify changing the field value. $new_url = 'https://www.drupal.org'; $new_title = $this->randomMachineName(); $new_class = $this->randomMachineName(); $entity->field_test->uri = $new_url; $entity->field_test->title = $new_title; $entity->field_test->first()->get('options')->set('query', NULL); $entity->field_test->first()->get('options')->set('attributes', array('class' => $new_class)); $this->assertEqual($entity->field_test->uri, $new_url); $this->assertEqual($entity->field_test->title, $new_title); $this->assertEqual($entity->field_test->options['attributes']['class'], $new_class); $this->assertNull($entity->field_test->options['query']); // Read changed entity and assert changed values. $entity->save(); $entity = EntityTest::load($id); $this->assertEqual($entity->field_test->uri, $new_url); $this->assertEqual($entity->field_test->title, $new_title); $this->assertEqual($entity->field_test->options['attributes']['class'], $new_class); // Check that if we only set uri the default values for title and options // are also initialized. $entity->field_test = ['uri' => 'internal:/node/add']; $this->assertEqual($entity->field_test->uri, 'internal:/node/add'); $this->assertNull($entity->field_test->title); $this->assertIdentical($entity->field_test->options, []); // Check that if set uri and serialize options then the default values are // properly initialized. $entity->field_test = ['uri' => 'internal:/node/add', 'options' => serialize(['query' => NULL])]; $this->assertEqual($entity->field_test->uri, 'internal:/node/add'); $this->assertNull($entity->field_test->title); $this->assertNull($entity->field_test->options['query']); // Check that if we set the direct value of link field it correctly set the // uri and the default values of the field. $entity->field_test = 'internal:/node/add'; $this->assertEqual($entity->field_test->uri, 'internal:/node/add'); $this->assertNull($entity->field_test->title); $this->assertIdentical($entity->field_test->options, []); // Check that setting options to NULL does not trigger an error when // calling getUrl(); $entity->field_test->options = NULL; $this->assertInstanceOf(Url::class, $entity->field_test[0]->getUrl()); // Check that setting LinkItem value NULL doesn't generate any error or // warning. $entity->field_test[0] = NULL; $this->assertNull($entity->field_test[0]->getValue()); // Test the generateSampleValue() method for generic, external, and internal // link types. $entity = EntityTest::create(); $entity->field_test->generateSampleItems(); $entity->field_test_external->generateSampleItems(); $entity->field_test_internal->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * Test creating a field with custom storage set. */ public function testCreateFieldCustomStorage() { $field_name = Unicode::strtolower($this->randomMachineName()); \Drupal::state()->set('field_test_custom_storage', $field_name); $field_storage = FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'test_field', 'custom_storage' => TRUE]); $field_storage->save(); $field = FieldConfig::create(['field_name' => $field_storage->getName(), 'entity_type' => 'entity_test', 'bundle' => 'entity_test']); $field->save(); \Drupal::entityManager()->clearCachedFieldDefinitions(); // Check that no table has been created for the field. $this->assertFalse(\Drupal::database()->schema()->tableExists('entity_test__' . $field_storage->getName())); // Save an entity with a value in the custom storage field and verify no // data is retrieved on load. $entity = EntityTest::create(['name' => $this->randomString(), $field_name => 'Test value']); $this->assertIdentical('Test value', $entity->{$field_name}->value, 'The test value is set on the field.'); $entity->save(); $entity = EntityTest::load($entity->id()); $this->assertNull($entity->{$field_name}->value, 'The loaded entity field value is NULL.'); }
/** * Tests date and time field. */ function testDatetimeField() { $field_name = $this->fieldStorage->getName(); // Change the field to a datetime field. $this->fieldStorage->setSetting('datetime_type', 'datetime'); $this->fieldStorage->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.'); $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.'); // Build up a date in the UTC timezone. $value = '2012-12-31 00:00:00'; $date = new DrupalDateTime($value, 'UTC'); // Update the timezone to the system default. $date->setTimezone(timezone_open(drupal_get_user_timezone())); // Submit a valid date and ensure it is accepted. $date_format = DateFormat::load('html_date')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern(); $edit = array("{$field_name}[0][value][date]" => $date->format($date_format), "{$field_name}[0][value][time]" => $date->format($time_format)); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); $this->assertRaw($date->format($date_format)); $this->assertRaw($date->format($time_format)); // Verify that the date is output according to the formatter settings. $options = array('format_type' => array('short', 'medium', 'long')); foreach ($options as $setting => $values) { foreach ($values as $new_value) { // Update the entity display settings. $this->displayOptions['settings'] = array($setting => $new_value) + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $this->renderTestEntity($id); switch ($setting) { case 'format_type': // Verify that a date is displayed. $expected = format_date($date->getTimestamp(), $new_value); $expected_iso = format_date($date->getTimestamp(), 'custom', 'Y-m-d\\TH:i:s\\Z', 'UTC'); $this->renderTestEntity($id); $this->assertFieldByXPath('//time[@datetime="' . $expected_iso . '"]', $expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected with %expected_iso attribute.', array('%value' => $new_value, '%expected' => $expected, '%expected_iso' => $expected_iso))); break; } } } // Verify that the plain formatter works. $this->displayOptions['type'] = 'datetime_plain'; $this->displayOptions['settings'] = $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT); $this->renderTestEntity($id); $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected))); // Verify that the 'datetime_custom' formatter works. $this->displayOptions['type'] = 'datetime_custom'; $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A') + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $date->format($this->displayOptions['settings']['date_format']); $this->renderTestEntity($id); $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected))); // Verify that the 'timezone_override' setting works. $this->displayOptions['type'] = 'datetime_custom'; $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York') + $this->defaultSettings; entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = $date->format($this->displayOptions['settings']['date_format'], array('timezone' => 'America/New_York')); $this->renderTestEntity($id); $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected))); // Verify that the 'datetime_time_ago' formatter works for intervals in the // past. First update the test entity so that the date difference always // has the same interval. Since the database always stores UTC, and the // interval will use this, force the test date to use UTC and not the local // or user timezome. $timestamp = REQUEST_TIME - 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); $entity->{$field_name}->value = $date->format(DATETIME_DATETIME_STORAGE_FORMAT); $entity->save(); $this->displayOptions['type'] = 'datetime_time_ago'; $this->displayOptions['settings'] = array('future_format' => '@interval from now', 'past_format' => '@interval earlier', 'granularity' => 3); entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = SafeMarkup::format($this->displayOptions['settings']['past_format'], ['@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])]); $this->renderTestEntity($id); $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); // Verify that the 'datetime_time_ago' formatter works for intervals in the // future. First update the test entity so that the date difference always // has the same interval. Since the database always stores UTC, and the // interval will use this, force the test date to use UTC and not the local // or user timezome. $timestamp = REQUEST_TIME + 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); $entity->{$field_name}->value = $date->format(DATETIME_DATETIME_STORAGE_FORMAT); $entity->save(); entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save(); $expected = SafeMarkup::format($this->displayOptions['settings']['future_format'], ['@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])]); $this->renderTestEntity($id); $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected))); }