/** * 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.'); }
/** * 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 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); }
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']); }
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 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); }
/** * 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); }
/** * 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.'); }
/** * 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); }
/** * 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); } }
/** * 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); }
/** * 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.'); }
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()); }
/** * @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()); }
/** * 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'); }
/** * 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); }
/** * {@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(); } } }
/** * Tests the cache tags from image formatters. */ function testImageFormatterCacheTags() { // Create a test entity with the image field set. $entity = EntityTest::create(['name' => $this->randomMachineName()]); $entity->{$this->fieldName}->generateSampleItems(2); $entity->save(); // Generate the render array to verify if the cache tags are as expected. $build = $this->display->build($entity); $this->assertEquals($entity->{$this->fieldName}[0]->entity->getCacheTags(), $build[$this->fieldName][0]['#cache']['tags'], 'First image cache tags is as expected'); $this->assertEquals($entity->{$this->fieldName}[1]->entity->getCacheTags(), $build[$this->fieldName][1]['#cache']['tags'], 'Second image cache tags is as expected'); }
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; }
/** * Tests the formatters. */ public function testFormatter() { $entity = EntityTest::create(); $entity->{$this->fieldName}->value = 1; $items = $entity->get($this->fieldName); $build = $items->view(); $this->assertEqual($build['#formatter'], 'list_default', 'Ensure to fall back to the default formatter.'); $this->assertEqual($build[0]['#markup'], 'One'); $build = $items->view(array('type' => 'list_key')); $this->assertEqual($build['#formatter'], 'list_key', 'The chosen formatter is used.'); $this->assertEqual((string) $build[0]['#markup'], 1); }
/** * 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); }
/** * {@inheritdoc} */ protected function setUpFixtures() { parent::setUpFixtures(); $this->installEntitySchema('user'); $this->installEntitySchema('entity_test'); // Create some test entities. for ($i = 0; $i < 5; $i++) { EntityTest::create(['name' => $this->randomString()])->save(); } // Create and admin user. $this->adminUser = $this->createUser([], FALSE, TRUE); }
/** * Tests string formatter output. */ public function testUuidStringFormatter() { $entity = EntityTest::create([]); $entity->save(); $uuid_field = $entity->get('uuid'); $render_array = $uuid_field->view([]); $this->assertIdentical($render_array[0]['#markup'], $entity->uuid(), 'The rendered UUID matches the entity UUID.'); $render_array = $uuid_field->view(['settings' => ['link_to_entity' => TRUE]]); $this->assertIdentical($render_array[0]['#type'], 'link'); $this->assertIdentical($render_array[0]['#title'], $entity->uuid()); $this->assertIdentical($render_array[0]['#url']->toString(), $entity->url()); }
protected function setUp() { parent::setUp(); $this->installConfig(array('filter')); $this->createTestField(); // Add the mapping. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:text')))->save(); // Set up test entity. $this->entity = EntityTest::create(); $this->entity->{$this->fieldName}->value = $this->testValue; $this->entity->{$this->fieldName}->summary = $this->testSummary; }
/** * {@inheritdoc} */ protected function setUpFixtures() { parent::setUpFixtures(); $this->installEntitySchema('user'); $this->installEntitySchema('entity_test'); $this->installConfig(['user']); // Create some test entities. for ($i = 0; $i < 5; $i++) { EntityTest::create(['name' => $this->randomString()])->save(); } // Create and admin user. $this->adminUser = $this->createUser(['view test entity'], FALSE, TRUE); Role::load(AccountInterface::ANONYMOUS_ROLE)->grantPermission('view test entity')->save(); }
/** * Tests link field URL validation. */ function testURLValidation() { $field_name = Unicode::strtolower($this->randomMachineName()); // Create a field with settings to validate. $this->fieldStorage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'link')); $this->fieldStorage->save(); $this->field = FieldConfig::create(['field_storage' => $this->fieldStorage, 'bundle' => 'entity_test', 'settings' => array('title' => DRUPAL_DISABLED, 'link_type' => LinkItemInterface::LINK_GENERIC)]); $this->field->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => 'link_default', 'settings' => array('placeholder_url' => 'http://example.com')))->save(); entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name, array('type' => 'link'))->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][uri]", '', 'Link URL field is displayed'); $this->assertRaw('placeholder="http://example.com"'); // Create a path alias. \Drupal::service('path.alias_storage')->save('/admin', '/a/path/alias'); // Create a node to test the link widget. $node = $this->drupalCreateNode(); // Create an entity with restricted view access. $entity_test_no_label_access = EntityTest::create(['name' => 'forbid_access']); $entity_test_no_label_access->save(); // Define some valid URLs (keys are the entered values, values are the // strings displayed to the user). $valid_external_entries = array('http://www.example.com/' => 'http://www.example.com/', 'http://www.example.com/strings_(string_within_parenthesis)' => 'http://www.example.com/strings_(string_within_parenthesis)', 'http://www.example.com/numbers_(9999)' => 'http://www.example.com/numbers_(9999)'); $valid_internal_entries = array('/entity_test/add' => '/entity_test/add', '/a/path/alias' => '/a/path/alias', '/' => '<front>', '/?example=llama' => '<front>?example=llama', '/#example' => '<front>#example', '<front>' => '<front>', '<front>#example' => '<front>#example', '<front>?example=llama' => '<front>?example=llama', '?example=llama' => '?example=llama', '#example' => '#example', $node->label() . ' (1)' => $node->label() . ' (1)', 'entity:node/1' => $node->label() . ' (1)', 'entity:entity_test/' . $entity_test_no_label_access->id() => '- Restricted access - (' . $entity_test_no_label_access->id() . ')', 'entity:user/999999' => 'entity:user/999999'); // Define some invalid URLs. $validation_error_1 = "The path '@link_path' is invalid."; $validation_error_2 = 'Manually entered paths should start with /, ? or #.'; $validation_error_3 = "The path '@link_path' is inaccessible."; $invalid_external_entries = array('invalid://not-a-valid-protocol' => $validation_error_1, 'http://' => $validation_error_1); $invalid_internal_entries = array('no-leading-slash' => $validation_error_2, 'entity:non_existing_entity_type/yar' => $validation_error_1, 'entity:user/invalid-parameter' => $validation_error_1); // Test external and internal URLs for 'link_type' = LinkItemInterface::LINK_GENERIC. $this->assertValidEntries($field_name, $valid_external_entries + $valid_internal_entries); $this->assertInvalidEntries($field_name, $invalid_external_entries + $invalid_internal_entries); // Test external URLs for 'link_type' = LinkItemInterface::LINK_EXTERNAL. $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL); $this->field->save(); $this->assertValidEntries($field_name, $valid_external_entries); $this->assertInvalidEntries($field_name, $valid_internal_entries + $invalid_external_entries); // Test external URLs for 'link_type' = LinkItemInterface::LINK_INTERNAL. $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL); $this->field->save(); $this->assertValidEntries($field_name, $valid_internal_entries); $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries); // Ensure that users with 'link to any page', don't apply access checking. $this->drupalLogin($this->drupalCreateUser(['view test entity', 'administer entity_test content'])); $this->assertValidEntries($field_name, ['/entity_test/add' => '/entity_test/add']); $this->assertInValidEntries($field_name, ['/admin' => $validation_error_3]); }
protected function setUp() { parent::setUp(); $this->createTestField(); $this->installConfig(array('filter')); // Add the mapping. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:interactionCount'), 'datatype_callback' => array('callable' => 'Drupal\\rdf\\Tests\\Field\\TestDataConverter::convertFoo')))->save(); // Set up test values. $this->testValue = $this->randomMachineName(); $this->entity = EntityTest::create(); $this->entity->{$this->fieldName}->value = $this->testValue; $this->entity->save(); $this->uri = $this->getAbsoluteUri($this->entity); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); /** @var \Drupal\Core\Entity\EntityDefinitionUpdateManager $update_manager */ $update_manager = $this->container->get('entity.definition_update_manager'); \Drupal::entityManager()->clearCachedDefinitions(); $update_manager->applyUpdates(); ViewTestData::createTestViews(get_class($this), array('comment_test_views')); \Drupal::state()->set('entity_test.views_data', ['entity_test' => ['test_text_access' => ['field' => ['id' => 'standard']]]]); $entity_1 = EntityTest::create(['test_text_access' => 'no access value']); $entity_1->save(); $entity_2 = EntityTest::create(['test_text_access' => 'ok to see this one']); $entity_2->save(); $this->drupalLogin($this->drupalCreateUser(['access content'])); }
public function testMethods() { $entity = EntityTest::create(); $uuid = $entity->uuid(); $this->uuidIndex->add($entity); $entry = $this->uuidIndex->get($uuid); $expected = ['entity_type_id' => 'entity_test', 'entity_id' => 0, 'revision_id' => 0, 'uuid' => $uuid, 'rev' => $entity->_rev->value, 'is_stub' => $entity->_rev->is_stub, 'status' => 'indexed']; $this->assertEqual($expected, $entry, 'Single entry is correct for an entity that was not yet saved.'); $entity->save(); $this->uuidIndex->add($entity); $entry = $this->uuidIndex->get($uuid); $expected = ['entity_type_id' => 'entity_test', 'entity_id' => 1, 'revision_id' => 1, 'uuid' => $uuid, 'rev' => $entity->_rev->value, 'is_stub' => $entity->_rev->is_stub, 'status' => 'available']; $this->assertEqual($expected, $entry, 'Single entry is correct for an entity that was saved.'); $entities = []; $uuid = []; $rev = []; $is_stub = []; $entity = $entities[] = EntityTest::create(); $uuid[] = $entity->uuid(); $rev[] = $entity->_rev->value; $is_stub[] = $entity->_rev->is_stub; $entity = $entities[] = EntityTest::create(); $uuid[] = $entity->uuid(); $rev[] = $entity->_rev->value; $is_stub[] = $entity->_rev->is_stub; $this->uuidIndex->addMultiple($entities); $expected = [$uuid[0] => ['entity_type_id' => 'entity_test', 'entity_id' => 0, 'revision_id' => 0, 'rev' => $rev[0], 'is_stub' => $is_stub[0], 'uuid' => $uuid[0], 'status' => 'indexed'], $uuid[1] => ['entity_type_id' => 'entity_test', 'entity_id' => 0, 'revision_id' => 0, 'rev' => $rev[1], 'is_stub' => $is_stub[1], 'uuid' => $uuid[1], 'status' => 'indexed']]; $entries = $this->uuidIndex->getMultiple([$uuid[0], $uuid[1]]); $this->assertEqual($expected, $entries, 'Multiple entries are correct.'); /** @var \Drupal\Core\Entity\EntityStorageInterface $workspace_storage */ $workspace_storage = $this->container->get('entity.manager')->getStorage('workspace'); // Create new workspaces and query those. $ws1 = $this->randomMachineName(); $workspace_storage->create(['id' => $ws1]); $ws2 = $this->randomMachineName(); $workspace_storage->create(['id' => $ws2]); $entity = EntityTest::create(); $uuid = $entity->uuid(); $rev = $entity->_rev->value; $is_stub = $entity->_rev->is_stub; $this->uuidIndex->useWorkspace($ws1)->add($entity); $entry = $this->uuidIndex->useWorkspace($ws2)->get($uuid); $this->assertTrue(empty($entry), 'New workspace is empty'); $this->uuidIndex->useWorkspace($ws2)->add($entity); $entry = $this->uuidIndex->useWorkspace($ws2)->get($uuid); $expected = ['entity_type_id' => 'entity_test', 'entity_id' => 0, 'revision_id' => 0, 'rev' => $rev, 'is_stub' => $is_stub, 'uuid' => $uuid, 'status' => 'indexed']; $this->assertEqual($expected, $entry, 'Entry was added and fetched from new workspace.'); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installSchema('system', ['key_value_expire']); \Drupal::service('router.builder')->rebuild(); $this->testUser = User::create(array('name' => 'foobar1', 'mail' => '*****@*****.**')); $this->testUser->save(); \Drupal::service('current_user')->setAccount($this->testUser); $this->testAutocreateUser = User::create(array('name' => 'foobar2', 'mail' => '*****@*****.**')); $this->testAutocreateUser->save(); for ($i = 1; $i < 3; $i++) { $entity = EntityTest::create(array('name' => $this->randomMachineName())); $entity->save(); $this->referencedEntities[] = $entity; } }