3 namespace Drupal\Tests\field\Kernel\EntityReference;
5 use Drupal\comment\Entity\Comment;
6 use Drupal\Component\Render\FormattableMarkup;
7 use Drupal\Component\Utility\Unicode;
8 use Drupal\Core\Field\FieldItemListInterface;
9 use Drupal\Core\Field\FieldItemInterface;
10 use Drupal\Core\Field\FieldStorageDefinitionInterface;
11 use Drupal\Core\StringTranslation\TranslatableMarkup;
12 use Drupal\Core\Language\LanguageInterface;
13 use Drupal\entity_test\Entity\EntityTest;
14 use Drupal\entity_test\Entity\EntityTestStringId;
15 use Drupal\field\Entity\FieldConfig;
16 use Drupal\field\Entity\FieldStorageConfig;
17 use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
18 use Drupal\node\NodeInterface;
19 use Drupal\Tests\field\Kernel\FieldKernelTestBase;
20 use Drupal\file\Entity\File;
21 use Drupal\node\Entity\Node;
22 use Drupal\taxonomy\Entity\Term;
23 use Drupal\taxonomy\Entity\Vocabulary;
24 use Drupal\user\Entity\User;
28 * Tests the new entity API for the entity reference field type.
30 * @group entity_reference
32 class EntityReferenceItemTest extends FieldKernelTestBase {
34 use EntityReferenceTestTrait;
41 public static $modules = ['node', 'comment', 'file', 'taxonomy', 'text', 'filter', 'views', 'field'];
44 * The taxonomy vocabulary to test with.
46 * @var \Drupal\taxonomy\VocabularyInterface
48 protected $vocabulary;
51 * The taxonomy term to test with.
53 * @var \Drupal\taxonomy\TermInterface
58 * The test entity with a string ID.
60 * @var \Drupal\entity_test\Entity\EntityTestStringId
62 protected $entityStringId;
67 protected function setUp() {
70 $this->installEntitySchema('entity_test_string_id');
71 $this->installEntitySchema('taxonomy_term');
72 $this->installEntitySchema('node');
73 $this->installEntitySchema('comment');
74 $this->installEntitySchema('file');
76 $this->installSchema('comment', ['comment_entity_statistics']);
77 $this->installSchema('node', ['node_access']);
79 $this->vocabulary = Vocabulary::create([
80 'name' => $this->randomMachineName(),
81 'vid' => Unicode::strtolower($this->randomMachineName()),
82 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
84 $this->vocabulary->save();
86 $this->term = Term::create([
87 'name' => $this->randomMachineName(),
88 'vid' => $this->vocabulary->id(),
89 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
93 $this->entityStringId = EntityTestStringId::create([
94 'id' => $this->randomMachineName(),
96 $this->entityStringId->save();
98 // Use the util to create an instance.
99 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_term', 'Test content entity reference', 'taxonomy_term');
100 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_entity_test_string_id', 'Test content entity reference with string ID', 'entity_test_string_id');
101 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_vocabulary', 'Test config entity reference', 'taxonomy_vocabulary');
102 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_node', 'Test node entity reference', 'node', 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
103 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_user', 'Test user entity reference', 'user');
104 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_comment', 'Test comment entity reference', 'comment');
105 $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_file', 'Test file entity reference', 'file');
109 * Tests the entity reference field type for referencing content entities.
111 public function testContentEntityReferenceItem() {
112 $tid = $this->term->id();
114 // Just being able to create the entity like this verifies a lot of code.
115 $entity = EntityTest::create();
116 $entity->field_test_taxonomy_term->target_id = $tid;
117 $entity->name->value = $this->randomMachineName();
120 $entity = EntityTest::load($entity->id());
121 $this->assertTrue($entity->field_test_taxonomy_term instanceof FieldItemListInterface, 'Field implements interface.');
122 $this->assertTrue($entity->field_test_taxonomy_term[0] instanceof FieldItemInterface, 'Field item implements interface.');
123 $this->assertEqual($entity->field_test_taxonomy_term->target_id, $tid);
124 $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $this->term->getName());
125 $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $tid);
126 $this->assertEqual($entity->field_test_taxonomy_term->entity->uuid(), $this->term->uuid());
127 // Verify that the label for the target ID property definition is correct.
128 $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
129 $this->assertTrue($label instanceof TranslatableMarkup);
130 $this->assertEqual($label->render(), 'Taxonomy term ID');
132 // Change the name of the term via the reference.
133 $new_name = $this->randomMachineName();
134 $entity->field_test_taxonomy_term->entity->setName($new_name);
135 $entity->field_test_taxonomy_term->entity->save();
136 // Verify it is the correct name.
137 $term = Term::load($tid);
138 $this->assertEqual($term->getName(), $new_name);
140 // Make sure the computed term reflects updates to the term id.
141 $term2 = Term::create([
142 'name' => $this->randomMachineName(),
143 'vid' => $this->term->bundle(),
144 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
148 // Test all the possible ways of assigning a value.
149 $entity->field_test_taxonomy_term->target_id = $term->id();
150 $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
151 $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());
153 $entity->field_test_taxonomy_term = [['target_id' => $term2->id()]];
154 $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term2->id());
155 $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());
157 // Test value assignment via the computed 'entity' property.
158 $entity->field_test_taxonomy_term->entity = $term;
159 $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term->id());
160 $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());
162 $entity->field_test_taxonomy_term = [['entity' => $term2]];
163 $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term2->id());
164 $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());
166 // Test assigning an invalid item throws an exception.
168 $entity->field_test_taxonomy_term = ['target_id' => 'invalid', 'entity' => $term2];
169 $this->fail('Assigning an invalid item throws an exception.');
171 catch (\InvalidArgumentException $e) {
172 $this->pass('Assigning an invalid item throws an exception.');
175 // Delete terms so we have nothing to reference and try again
178 $entity = EntityTest::create(['name' => $this->randomMachineName()]);
181 // Test the generateSampleValue() method.
182 $entity = EntityTest::create();
183 $entity->field_test_taxonomy_term->generateSampleItems();
184 $entity->field_test_taxonomy_vocabulary->generateSampleItems();
185 $this->entityValidateAndSave($entity);
187 // Tests that setting an integer target ID together with an entity object
188 // succeeds and does not cause any exceptions. There is no assertion here,
189 // as the assignment should not throw any exceptions and if it does the
191 // @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
192 $user = User::create(['name' => $this->randomString()]);
194 $entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
198 * Tests referencing content entities with string IDs.
200 public function testContentEntityReferenceItemWithStringId() {
201 $entity = EntityTest::create();
202 $entity->field_test_entity_test_string_id->target_id = $this->entityStringId->id();
204 $storage = \Drupal::entityManager()->getStorage('entity_test');
205 $storage->resetCache();
206 $this->assertEqual($this->entityStringId->id(), $storage->load($entity->id())->field_test_entity_test_string_id->target_id);
207 // Verify that the label for the target ID property definition is correct.
208 $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
209 $this->assertTrue($label instanceof TranslatableMarkup);
210 $this->assertEqual($label->render(), 'Taxonomy term ID');
214 * Tests the entity reference field type for referencing config entities.
216 public function testConfigEntityReferenceItem() {
217 $referenced_entity_id = $this->vocabulary->id();
219 // Just being able to create the entity like this verifies a lot of code.
220 $entity = EntityTest::create();
221 $entity->field_test_taxonomy_vocabulary->target_id = $referenced_entity_id;
222 $entity->name->value = $this->randomMachineName();
225 $entity = EntityTest::load($entity->id());
226 $this->assertTrue($entity->field_test_taxonomy_vocabulary instanceof FieldItemListInterface, 'Field implements interface.');
227 $this->assertTrue($entity->field_test_taxonomy_vocabulary[0] instanceof FieldItemInterface, 'Field item implements interface.');
228 $this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id);
229 $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $this->vocabulary->label());
230 $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $referenced_entity_id);
231 $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->uuid(), $this->vocabulary->uuid());
233 // Change the name of the term via the reference.
234 $new_name = $this->randomMachineName();
235 $entity->field_test_taxonomy_vocabulary->entity->set('name', $new_name);
236 $entity->field_test_taxonomy_vocabulary->entity->save();
237 // Verify it is the correct name.
238 $vocabulary = Vocabulary::load($referenced_entity_id);
239 $this->assertEqual($vocabulary->label(), $new_name);
241 // Make sure the computed term reflects updates to the term id.
242 $vocabulary2 = $vocabulary = Vocabulary::create([
243 'name' => $this->randomMachineName(),
244 'vid' => Unicode::strtolower($this->randomMachineName()),
245 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
247 $vocabulary2->save();
249 $entity->field_test_taxonomy_vocabulary->target_id = $vocabulary2->id();
250 $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $vocabulary2->id());
251 $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $vocabulary2->label());
253 // Delete terms so we have nothing to reference and try again
254 $this->vocabulary->delete();
255 $vocabulary2->delete();
256 $entity = EntityTest::create(['name' => $this->randomMachineName()]);
261 * Tests entity auto create.
263 public function testEntityAutoCreate() {
264 // The term entity is unsaved here.
265 $term = Term::create([
266 'name' => $this->randomMachineName(),
267 'vid' => $this->term->bundle(),
268 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
270 $entity = EntityTest::create();
271 // Now assign the unsaved term to the field.
272 $entity->field_test_taxonomy_term->entity = $term;
273 $entity->name->value = $this->randomMachineName();
274 // This is equal to storing an entity to tempstore or cache and retrieving
275 // it back. An example for this is node preview.
276 $entity = serialize($entity);
277 $entity = unserialize($entity);
278 // And then the entity.
280 $term = \Drupal::entityManager()->loadEntityByUuid($term->getEntityTypeId(), $term->uuid());
281 $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
285 * Test saving order sequence doesn't matter.
287 public function testEntitySaveOrder() {
288 // The term entity is unsaved here.
289 $term = Term::create([
290 'name' => $this->randomMachineName(),
291 'vid' => $this->term->bundle(),
292 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
294 $entity = EntityTest::create();
295 // Now assign the unsaved term to the field.
296 $entity->field_test_taxonomy_term->entity = $term;
297 $entity->name->value = $this->randomMachineName();
298 // Now get the field value.
299 $value = $entity->get('field_test_taxonomy_term');
300 $this->assertTrue(empty($value['target_id']));
301 $this->assertNull($entity->field_test_taxonomy_term->target_id);
303 $entity->field_test_taxonomy_term = $value;
304 // Now save the term.
306 // And then the entity.
308 $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
312 * Tests that the 'handler' field setting stores the proper plugin ID.
314 public function testSelectionHandlerSettings() {
315 $field_name = Unicode::strtolower($this->randomMachineName());
316 $field_storage = FieldStorageConfig::create([
317 'field_name' => $field_name,
318 'entity_type' => 'entity_test',
319 'type' => 'entity_reference',
321 'target_type' => 'entity_test'
324 $field_storage->save();
326 // Do not specify any value for the 'handler' setting in order to verify
327 // that the default handler with the correct derivative is used.
328 $field = FieldConfig::create([
329 'field_storage' => $field_storage,
330 'bundle' => 'entity_test',
333 $field = FieldConfig::load($field->id());
334 $this->assertEqual($field->getSetting('handler'), 'default:entity_test');
336 // Change the target_type in the field storage, and check that the handler
337 // was correctly reassigned in the field.
338 $field_storage->setSetting('target_type', 'entity_test_rev');
339 $field_storage->save();
340 $field = FieldConfig::load($field->id());
341 $this->assertEqual($field->getSetting('handler'), 'default:entity_test_rev');
343 // Change the handler to another, non-derivative plugin.
344 $field->setSetting('handler', 'views');
346 $field = FieldConfig::load($field->id());
347 $this->assertEqual($field->getSetting('handler'), 'views');
349 // Change the target_type in the field storage again, and check that the
350 // non-derivative handler was unchanged.
351 $field_storage->setSetting('target_type', 'entity_test_rev');
352 $field_storage->save();
353 $field = FieldConfig::load($field->id());
354 $this->assertEqual($field->getSetting('handler'), 'views');
358 * Tests ValidReferenceConstraint with newly created and unsaved entities.
360 public function testAutocreateValidation() {
361 // The term entity is unsaved here.
362 $term = Term::create([
363 'name' => $this->randomMachineName(),
364 'vid' => $this->term->bundle(),
365 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
367 $entity = EntityTest::create([
368 'field_test_taxonomy_term' => [
373 $errors = $entity->validate();
374 // Using target_id of NULL is valid with an unsaved entity.
375 $this->assertEqual(0, count($errors));
376 // Using target_id of NULL is not valid with a saved entity.
378 $entity = EntityTest::create([
379 'field_test_taxonomy_term' => [
384 $errors = $entity->validate();
385 $this->assertEqual(1, count($errors));
386 $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.');
387 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0');
388 // This should rectify the issue, favoring the entity over the target_id.
390 $errors = $entity->validate();
391 $this->assertEqual(0, count($errors));
393 // Test with an unpublished and unsaved node.
394 $title = $this->randomString();
395 $node = Node::create([
398 'status' => NodeInterface::NOT_PUBLISHED,
401 $entity = EntityTest::create([
402 'field_test_node' => [
407 $errors = $entity->validate();
408 $this->assertEqual(1, count($errors));
409 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $title]));
410 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
412 // Publish the node and try again.
413 $node->setPublished(TRUE);
414 $errors = $entity->validate();
415 $this->assertEqual(0, count($errors));
417 // Test with a mix of valid and invalid nodes.
418 $unsaved_unpublished_node_title = $this->randomString();
419 $unsaved_unpublished_node = Node::create([
420 'title' => $unsaved_unpublished_node_title,
422 'status' => NodeInterface::NOT_PUBLISHED,
425 $saved_unpublished_node_title = $this->randomString();
426 $saved_unpublished_node = Node::create([
427 'title' => $saved_unpublished_node_title,
429 'status' => NodeInterface::NOT_PUBLISHED,
431 $saved_unpublished_node->save();
433 $saved_published_node_title = $this->randomString();
434 $saved_published_node = Node::create([
435 'title' => $saved_published_node_title,
437 'status' => NodeInterface::PUBLISHED,
439 $saved_published_node->save();
441 $entity = EntityTest::create([
442 'field_test_node' => [
444 'entity' => $unsaved_unpublished_node,
447 'target_id' => $saved_unpublished_node->id(),
450 'target_id' => $saved_published_node->id(),
455 $errors = $entity->validate();
456 $this->assertEqual(2, count($errors));
457 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
458 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
459 $this->assertEqual($errors[1]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $saved_unpublished_node->id()]));
460 $this->assertEqual($errors[1]->getPropertyPath(), 'field_test_node.1.target_id');
462 // Publish one of the nodes and try again.
463 $saved_unpublished_node->setPublished(TRUE);
464 $saved_unpublished_node->save();
465 $errors = $entity->validate();
466 $this->assertEqual(1, count($errors));
467 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
468 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
470 // Publish the last invalid node and try again.
471 $unsaved_unpublished_node->setPublished(TRUE);
472 $errors = $entity->validate();
473 $this->assertEqual(0, count($errors));
475 // Test with an unpublished and unsaved comment.
476 $title = $this->randomString();
477 $comment = Comment::create([
479 'comment_type' => 'comment',
483 $entity = EntityTest::create([
484 'field_test_comment' => [
485 'entity' => $comment,
489 $errors = $entity->validate();
490 $this->assertEqual(1, count($errors));
491 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'comment', '%label' => $title]));
492 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_comment.0.entity');
494 // Publish the comment and try again.
495 $comment->setPublished(TRUE);
496 $errors = $entity->validate();
497 $this->assertEqual(0, count($errors));
499 // Test with an inactive and unsaved user.
500 $name = $this->randomString();
501 $user = User::create([
506 $entity = EntityTest::create([
507 'field_test_user' => [
512 $errors = $entity->validate();
513 $this->assertEqual(1, count($errors));
514 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'user', '%label' => $name]));
515 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_user.0.entity');
517 // Activate the user and try again.
519 $errors = $entity->validate();
520 $this->assertEqual(0, count($errors));
522 // Test with a temporary and unsaved file.
523 $filename = $this->randomMachineName() . '.txt';
524 $file = File::create([
525 'filename' => $filename,
529 $entity = EntityTest::create([
530 'field_test_file' => [
535 $errors = $entity->validate();
536 $this->assertEqual(1, count($errors));
537 $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'file', '%label' => $filename]));
538 $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_file.0.entity');
540 // Set the file as permanent and try again.
541 $file->setPermanent();
542 $errors = $entity->validate();
543 $this->assertEqual(0, count($errors));