/** * Checks that the saved field item value matches the expected one. * * @param \Drupal\entity_test\Entity\EntityTest $entity * The test entity. * @param $expected_value * The expected field item value. * * @return bool * TRUE if the item value matches expectations, FALSE otherwise. */ protected function assertSavedFieldItemValue(EntityTest $entity, $expected_value) { $entity->setNewRevision(TRUE); $entity->save(); $base_field_expected_value = str_replace($this->fieldName, 'field_test_item', $expected_value); $result = $this->assertEqual($entity->field_test_item->value, $base_field_expected_value); $result = $result && $this->assertEqual($entity->{$this->fieldName}->value, $expected_value); $entity = $this->reloadEntity($entity); $result = $result && $this->assertEqual($entity->field_test_item->value, $base_field_expected_value); $result = $result && $this->assertEqual($entity->{$this->fieldName}->value, $expected_value); return $result; }
/** * 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); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['name']->setDisplayOptions('form', array('type' => 'string', 'weight' => 0)); $fields['type']->setDisplayOptions('form', array('type' => 'entity_reference_autocomplete', 'weight' => 0)); return $fields; }
/** * Test hook_entity_display_build_alter(). */ public function testHookEntityDisplayBuildAlter() { entity_test_create_bundle('display_build_alter_bundle'); /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); $entity_ids = []; // Create some entities to test. for ($i = 0; $i < 5; $i++) { $entity = EntityTest::create(['name' => $this->randomMachineName(), 'type' => 'display_build_alter_bundle']); $entity->save(); $entity_ids[] = $entity->id(); } /** @var \Drupal\entity_test\EntityTestViewBuilder $view_builder */ $view_builder = $this->container->get('entity_type.manager')->getViewBuilder('entity_test'); /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */ $storage = $this->container->get('entity_type.manager')->getStorage('entity_test'); $storage->resetCache(); $entities = $storage->loadMultiple($entity_ids); $build = $view_builder->viewMultiple($entities); $output = $renderer->renderRoot($build); $this->setRawContent($output->__toString()); // Confirm that the content added in // entity_test_entity_display_build_alter() appears multiple times, not // just for the final entity. foreach ($entity_ids as $id) { $this->assertText('Content added in hook_entity_display_build_alter for entity id ' . $id); } }
/** * Tests the missing content event is fired. * * @see \Drupal\Core\Config\ConfigImporter::processMissingContent() * @see \Drupal\config_import_test\EventSubscriber */ function testMissingContent() { \Drupal::state()->set('config_import_test.config_import_missing_content', TRUE); // Update a configuration entity in the sync directory to have a dependency // on two content entities that do not exist. $storage = $this->container->get('config.storage'); $sync = $this->container->get('config.storage.sync'); $entity_one = EntityTest::create(array('name' => 'one')); $entity_two = EntityTest::create(array('name' => 'two')); $entity_three = EntityTest::create(array('name' => 'three')); $dynamic_name = 'config_test.dynamic.dotted.default'; $original_dynamic_data = $storage->read($dynamic_name); // Entity one will be resolved by // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentOne(). $original_dynamic_data['dependencies']['content'][] = $entity_one->getConfigDependencyName(); // Entity two will be resolved by // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentTwo(). $original_dynamic_data['dependencies']['content'][] = $entity_two->getConfigDependencyName(); // Entity three will be resolved by // \Drupal\Core\Config\Importer\FinalMissingContentSubscriber. $original_dynamic_data['dependencies']['content'][] = $entity_three->getConfigDependencyName(); $sync->write($dynamic_name, $original_dynamic_data); // Import. $this->configImporter->reset()->import(); $this->assertEqual([], $this->configImporter->getErrors(), 'There were no errors during the import.'); $this->assertEqual($entity_one->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_one'), 'The missing content event is fired during configuration import.'); $this->assertEqual($entity_two->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_two'), 'The missing content event is fired during configuration import.'); $original_dynamic_data = $storage->read($dynamic_name); $this->assertEqual([$entity_one->getConfigDependencyName(), $entity_two->getConfigDependencyName(), $entity_three->getConfigDependencyName()], $original_dynamic_data['dependencies']['content'], 'The imported configuration entity has the missing content entity dependency.'); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['custom_langcode_key'] = $fields['langcode']; unset($fields['langcode']); return $fields; }
/** * 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.'); }
/** * 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'); }
public function testUI() { // Set up a block and a entity_test entity. $block = Block::create(['id' => 'test_id', 'plugin' => 'system_main_block']); $block->save(); $entity_test = EntityTest::create(['bundle' => 'entity_test']); $entity_test->save(); $default = $this->randomView([]); $id = $default['id']; $view = View::load($id); $this->drupalGet($view->urlInfo('edit-form')); // Add a global NULL argument to the view for testing argument placeholders. $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/argument", ['name[views.null]' => 1], 'Add and configure contextual filters'); $this->drupalPostForm(NULL, [], 'Apply'); // Configure both the entity_test area header and the block header to // reference the given entities. $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/header", ['name[views.entity_block]' => 1], 'Add and configure header'); $this->drupalPostForm(NULL, ['options[target]' => $block->id()], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/header", ['name[views.entity_entity_test]' => 1], 'Add and configure header'); $this->drupalPostForm(NULL, ['options[target]' => $entity_test->id()], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm the correct target identifiers were saved for both entities. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual($block->id(), $header['entity_block']['target']); $this->assertEqual($entity_test->uuid(), $header['entity_entity_test']['target']); // Confirm that the correct serial ID (for the entity_test) and config ID // (for the block) are displayed in the form. $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block"); $this->assertFieldByName('options[target]', $block->id()); $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test"); $this->assertFieldByName('options[target]', $entity_test->id()); // Replace the header target entities with argument placeholders. $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block", ['options[target]' => '{{ raw_arguments.null }}'], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test", ['options[target]' => '{{ raw_arguments.null }}'], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm that the argument placeholders are saved. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual('{{ raw_arguments.null }}', $header['entity_block']['target']); $this->assertEqual('{{ raw_arguments.null }}', $header['entity_entity_test']['target']); // Confirm that the argument placeholders are still displayed in the form. $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block"); $this->assertFieldByName('options[target]', '{{ raw_arguments.null }}'); $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test"); $this->assertFieldByName('options[target]', '{{ raw_arguments.null }}'); // Change the targets for both headers back to the entities. $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block", ['options[target]' => $block->id()], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test", ['options[target]' => $entity_test->id()], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm the targets were again saved correctly and not skipped based on // the previous form value. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual($block->id(), $header['entity_block']['target']); $this->assertEqual($entity_test->uuid(), $header['entity_entity_test']['target']); }
/** * 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 email field type. */ public function testEmailItem() { // Verify entity creation. $entity = EntityTest::create(); $value = '*****@*****.**'; $entity->field_email = $value; $entity->name->value = $this->randomMachineName(); $entity->save(); // Verify entity has been created properly. $id = $entity->id(); $entity = entity_load('entity_test', $id); $this->assertTrue($entity->field_email instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_email[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_email->value, $value); $this->assertEqual($entity->field_email[0]->value, $value); // Verify changing the email value. $new_value = $this->randomMachineName(); $entity->field_email->value = $new_value; $this->assertEqual($entity->field_email->value, $new_value); // Read changed entity and assert changed values. $entity->save(); $entity = entity_load('entity_test', $id); $this->assertEqual($entity->field_email->value, $new_value); // Test sample item generation. $entity = EntityTest::create(); $entity->field_email->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['name']->setDisplayOptions('form', array('type' => 'string', 'weight' => 0)); $fields['name']->addConstraint('FieldWidgetConstraint', array()); return $fields; }
/** * 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 = entity_load('entity_test', $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 = entity_load('entity_test', $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); }
protected function setUp() { parent::setUp(); $this->installEntitySchema('taxonomy_term'); // We want an entity reference field. It needs a vocabulary, terms, a field // storage and a field. First, create the vocabulary. $vocabulary = Vocabulary::create(['vid' => Unicode::strtolower($this->randomMachineName())]); $vocabulary->save(); // Second, create the field. entity_test_create_bundle('test_bundle'); $this->fieldName = strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('entity_test', 'test_bundle', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { $term = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocabulary->id()]); $term->save(); $this->terms[] = $term; $this->accounts[] = $this->createUser(); } // Create three entity_test entities, the 0th entity will point to the // 0th account and 0th term, the 1st and 2nd entity will point to the // 1st account and 1st term. for ($i = 0; $i <= 2; $i++) { $entity = EntityTest::create(array('type' => 'test_bundle')); $entity->name->value = $this->randomMachineName(); $index = $i ? 1 : 0; $entity->user_id->target_id = $this->accounts[$index]->id(); $entity->{$this->fieldName}->target_id = $this->terms[$index]->id(); $entity->save(); $this->entities[] = $entity; } $this->factory = \Drupal::service('entity.query'); }
/** * Tests the normalize function. */ public function testNormalize() { $target_entity_de = EntityTest::create(array('langcode' => 'de', 'field_test_entity_reference' => NULL)); $target_entity_de->save(); $target_entity_en = EntityTest::create(array('langcode' => 'en', 'field_test_entity_reference' => NULL)); $target_entity_en->save(); // Create a German entity. $values = array('langcode' => 'de', 'name' => $this->randomMachineName(), 'field_test_text' => array('value' => $this->randomMachineName(), 'format' => 'full_html'), 'field_test_entity_reference' => array('target_id' => $target_entity_de->id())); // Array of translated values. $translation_values = array('name' => $this->randomMachineName(), 'field_test_entity_reference' => array('target_id' => $target_entity_en->id())); $entity = EntityTest::create($values); $entity->save(); // Add an English value for name and entity reference properties. $entity->addTranslation('en')->set('name', array(0 => array('value' => $translation_values['name']))); $entity->getTranslation('en')->set('field_test_entity_reference', array(0 => $translation_values['field_test_entity_reference'])); $entity->save(); $type_uri = Url::fromUri('base:rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(); $relation_uri = Url::fromUri('base:rest/relation/entity_test/entity_test/field_test_entity_reference', array('absolute' => TRUE))->toString(); $expected_array = array('_links' => array('curies' => array(array('href' => '/relations', 'name' => 'site', 'templated' => TRUE)), 'self' => array('href' => $this->getEntityUri($entity)), 'type' => array('href' => $type_uri), $relation_uri => array(array('href' => $this->getEntityUri($target_entity_de), 'lang' => 'de'), array('href' => $this->getEntityUri($target_entity_en), 'lang' => 'en'))), '_embedded' => array($relation_uri => array(array('_links' => array('self' => array('href' => $this->getEntityUri($target_entity_de)), 'type' => array('href' => $type_uri)), 'uuid' => array(array('value' => $target_entity_de->uuid())), 'lang' => 'de'), array('_links' => array('self' => array('href' => $this->getEntityUri($target_entity_en)), 'type' => array('href' => $type_uri)), 'uuid' => array(array('value' => $target_entity_en->uuid())), 'lang' => 'en'))), 'id' => array(array('value' => $entity->id())), 'uuid' => array(array('value' => $entity->uuid())), 'langcode' => array(array('value' => 'de')), 'name' => array(array('value' => $values['name'], 'lang' => 'de'), array('value' => $translation_values['name'], 'lang' => 'en')), 'field_test_text' => array(array('value' => $values['field_test_text']['value'], 'format' => $values['field_test_text']['format']))); $normalized = $this->serializer->normalize($entity, $this->format); $this->assertEqual($normalized['_links']['self'], $expected_array['_links']['self'], 'self link placed correctly.'); // @todo Test curies. // @todo Test type. $this->assertEqual($normalized['id'], $expected_array['id'], 'Internal id is exposed.'); $this->assertEqual($normalized['uuid'], $expected_array['uuid'], 'Non-translatable fields is normalized.'); $this->assertEqual($normalized['name'], $expected_array['name'], 'Translatable field with multiple language values is normalized.'); $this->assertEqual($normalized['field_test_text'], $expected_array['field_test_text'], 'Field with properties is normalized.'); $this->assertEqual($normalized['_embedded'][$relation_uri], $expected_array['_embedded'][$relation_uri], 'Entity reference field is normalized.'); $this->assertEqual($normalized['_links'][$relation_uri], $expected_array['_links'][$relation_uri], 'Links are added for entity reference field.'); }
/** * Tests field item attributes. */ public function testFieldItemAttributes() { // Make sure the test field will be rendered. entity_get_display('entity_test', 'entity_test', 'default')->setComponent('field_test_text', array('type' => 'text_default'))->save(); // Create an entity and save test value in field_test_text. $test_value = $this->randomMachineName(); $entity = EntityTest::create(); $entity->field_test_text = $test_value; $entity->save(); // Browse to the entity and verify that the attribute is rendered in the // field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar"]/p[text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attribute has been found in the rendered output of the field.'); // Enable the RDF module to ensure that two modules can add attributes to // the same field item. \Drupal::service('module_installer')->install(array('rdf')); $this->resetAll(); // Set an RDF mapping for the field_test_text field. This RDF mapping will // be turned into RDFa attributes in the field item output. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping('field_test_text', array('properties' => array('schema:text')))->save(); // Browse to the entity and verify that the attributes from both modules // are rendered in the field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar" and @property="schema:text"]/p[text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attributes from both modules have been found in the rendered output of the field.'); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['test_no_display'] = BaseFieldDefinition::create('text')->setLabel(t('Field with no display')); $fields['test_display_configurable'] = BaseFieldDefinition::create('text')->setLabel(t('Field with configurable display'))->setDisplayOptions('view', array('type' => 'text_default', 'weight' => 10))->setDisplayConfigurable('view', TRUE)->setDisplayOptions('form', array('type' => 'text_textfield', 'weight' => 10))->setDisplayConfigurable('form', TRUE); $fields['test_display_non_configurable'] = BaseFieldDefinition::create('text')->setLabel(t('Field with non-configurable display'))->setDisplayOptions('view', array('type' => 'text_default', 'weight' => 11))->setDisplayOptions('form', array('type' => 'text_textfield', 'weight' => 11)); return $fields; }
/** * Test that allowed values can be updated. */ function testUpdateAllowedValues() { // All three options appear. $entity = EntityTest::create(); $form = \Drupal::service('entity.form_builder')->getForm($entity); $this->assertTrue(!empty($form[$this->fieldName]['widget'][1]), 'Option 1 exists'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][2]), 'Option 2 exists'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][3]), 'Option 3 exists'); // Use one of the values in an actual entity, and check that this value // cannot be removed from the list. $entity = EntityTest::create(); $entity->{$this->fieldName}->value = 1; $entity->save(); $this->fieldStorage->setSetting('allowed_values', [2 => 'Two']); try { $this->fieldStorage->save(); $this->fail(t('Cannot update a list field storage to not include keys with existing data.')); } catch (FieldStorageDefinitionUpdateForbiddenException $e) { $this->pass(t('Cannot update a list field storage to not include keys with existing data.')); } // Empty the value, so that we can actually remove the option. unset($entity->{$this->fieldName}); $entity->save(); // Removed options do not appear. $this->fieldStorage->setSetting('allowed_values', [2 => 'Two']); $this->fieldStorage->save(); $entity = EntityTest::create(); $form = \Drupal::service('entity.form_builder')->getForm($entity); $this->assertTrue(empty($form[$this->fieldName]['widget'][1]), 'Option 1 does not exist'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][2]), 'Option 2 exists'); $this->assertTrue(empty($form[$this->fieldName]['widget'][3]), 'Option 3 does not exist'); // Completely new options appear. $this->fieldStorage->setSetting('allowed_values', [10 => 'Update', 20 => 'Twenty']); $this->fieldStorage->save(); // The entity holds an outdated field object with the old allowed values // setting, so we need to reinitialize the entity object. $entity = EntityTest::create(); $form = \Drupal::service('entity.form_builder')->getForm($entity); $this->assertTrue(empty($form[$this->fieldName]['widget'][1]), 'Option 1 does not exist'); $this->assertTrue(empty($form[$this->fieldName]['widget'][2]), 'Option 2 does not exist'); $this->assertTrue(empty($form[$this->fieldName]['widget'][3]), 'Option 3 does not exist'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][10]), 'Option 10 exists'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][20]), 'Option 20 exists'); // Options are reset when a new field with the same name is created. $this->fieldStorage->delete(); FieldStorageConfig::create($this->fieldStorageDefinition)->save(); FieldConfig::create(['field_name' => $this->fieldName, 'entity_type' => 'entity_test', 'bundle' => 'entity_test', 'required' => TRUE])->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($this->fieldName, array('type' => 'options_buttons'))->save(); $entity = EntityTest::create(); $form = \Drupal::service('entity.form_builder')->getForm($entity); $this->assertTrue(!empty($form[$this->fieldName]['widget'][1]), 'Option 1 exists'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][2]), 'Option 2 exists'); $this->assertTrue(!empty($form[$this->fieldName]['widget'][3]), 'Option 3 exists'); // Test the generateSampleValue() method. $entity = EntityTest::create(); $entity->{$this->fieldName}->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * {@inheritdoc} */ public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) { $fields = parent::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions); if ($bundle == 'some_test_bundle') { $fields['name'] = clone $base_field_definitions['name']; $fields['name']->setDescription('Custom description.'); } return $fields; }
/** * 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 = entity_load('entity_test', $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.'); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['revision_id'] = FieldDefinition::create('integer')->setLabel(t('Revision ID'))->setDescription(t('The version id of the test entity.'))->setReadOnly(TRUE)->setSetting('unsigned', TRUE); $fields['langcode']->setRevisionable(TRUE); $fields['name']->setRevisionable(TRUE); $fields['user_id']->setRevisionable(TRUE); return $fields; }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['test_no_display'] = BaseFieldDefinition::create('text')->setLabel(t('Field with no display')); $fields['test_display_configurable'] = BaseFieldDefinition::create('text')->setLabel(t('Field with configurable display'))->setDisplayOptions('view', array('type' => 'text_default', 'weight' => 10))->setDisplayConfigurable('view', TRUE)->setDisplayOptions('form', array('type' => 'text_textfield', 'weight' => 10))->setDisplayConfigurable('form', TRUE); $fields['test_display_non_configurable'] = BaseFieldDefinition::create('text')->setLabel(t('Field with non-configurable display'))->setDisplayOptions('view', array('type' => 'text_default', 'weight' => 11))->setDisplayOptions('form', array('type' => 'text_textfield', 'weight' => 11)); $fields['test_display_multiple'] = BaseFieldDefinition::create('text')->setLabel(t('A field with multiple values'))->setCardinality(FieldStorageDefinition::CARDINALITY_UNLIMITED)->setDisplayOptions('view', array('type' => 'text_default', 'weight' => 12))->setDisplayOptions('form', array('type' => 'text_textfield', 'weight' => 12)); return $fields; }
public function testEntityTestFields() { $entity_test = EntityTest::create(['name' => 'test entity name']); $entity_test->save(); // @todo Expand the test coverage in https://www.drupal.org/node/2464635 $this->assertFieldAccess('entity_test', 'id', $entity_test->id()); $this->assertFieldAccess('entity_test', 'langcode', $entity_test->language()->getName()); $this->assertFieldAccess('entity_test', 'name', $entity_test->getName()); }
/** * {@inheritdoc} */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type); $fields['revision_id'] = BaseFieldDefinition::create('integer')->setLabel(t('Revision ID'))->setDescription(t('The version id of the test entity.'))->setReadOnly(TRUE)->setSetting('unsigned', TRUE); $fields['langcode']->setRevisionable(TRUE); $fields['name']->setRevisionable(TRUE); $fields['user_id']->setRevisionable(TRUE); $fields['non_rev_field'] = BaseFieldDefinition::create('string')->setLabel(t('Non Revisionable Field'))->setDescription(t('A non-revisionable test field.'))->setRevisionable(FALSE)->setTranslatable(TRUE)->setCardinality(1)->setReadOnly(TRUE); return $fields; }
/** * Ensures that entity URLs in a language have the right language prefix. */ public function testEntityUrlLanguage() { $entity = EntityTest::create(); $entity->addTranslation('es', ['name' => 'name spanish']); $entity->addTranslation('fr', ['name' => 'name french']); $entity->save(); $this->assertTrue(strpos($entity->urlInfo()->toString(), '/en/entity_test/' . $entity->id()) !== FALSE); $this->assertTrue(strpos($entity->getTranslation('es')->urlInfo()->toString(), '/es/entity_test/' . $entity->id()) !== FALSE); $this->assertTrue(strpos($entity->getTranslation('fr')->urlInfo()->toString(), '/fr/entity_test/' . $entity->id()) !== FALSE); }
/** * Tests all formatters with link to frontpage. */ public function testAllFormattersFront() { // Set up test values. $this->testValue = '/'; $this->entity = EntityTest::create(array()); $this->entity->{$this->fieldName}->uri = 'internal:/'; // Set up the expected result. $expected_rdf = array('value' => $this->uri . '/', 'type' => 'uri'); $this->runTestAllFormatters($expected_rdf, 'front'); }
/** * @covers ::convert */ public function testConvertNonRevisionableEntityType() { $entity_test = EntityTest::create(['name' => 'test']); $entity_test->save(); /** @var \Symfony\Component\Routing\RouterInterface $router */ $router = \Drupal::service('router.no_access_checks'); $result = $router->match('/entity_test/' . $entity_test->id()); $this->assertInstanceOf(EntityTest::class, $result['entity_test']); $this->assertEquals($entity_test->getRevisionId(), $result['entity_test']->getRevisionId()); }
protected function setUp() { parent::setUp(); $this->createTestField(); // Add the mapping. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:dateCreated')))->save(); // Set up test entity. $this->entity = EntityTest::create(array()); $this->entity->{$this->fieldName}->value = $this->testValue; }
/** * {@inheritdoc} */ protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); // Create 5 entities per bundle, to allow a summary overview per bundle. for ($i = 0; $i < 5; $i++) { for ($j = 0; $j < 5; $j++) { $this->entities[] = $entity = EntityTest::create(['name' => 'Entity ' . ($i * 5 + $j), 'type' => 'type' . $i]); $entity->save(); } } }