3 namespace Drupal\Tests\field\Kernel\EntityReference;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;
9 use Drupal\field\Entity\FieldConfig;
10 use Drupal\field\Entity\FieldStorageConfig;
11 use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
12 use Drupal\filter\Entity\FilterFormat;
13 use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
14 use Drupal\user\Entity\Role;
15 use Drupal\user\RoleInterface;
16 use Drupal\entity_test\Entity\EntityTestLabel;
19 * Tests the formatters functionality.
21 * @group entity_reference
23 class EntityReferenceFormatterTest extends EntityKernelTestBase {
25 use EntityReferenceTestTrait;
28 * The entity type used in this test.
32 protected $entityType = 'entity_test';
35 * The bundle used in this test.
39 protected $bundle = 'entity_test';
42 * The name of the field used in this test.
46 protected $fieldName = 'field_test';
49 * The entity to be referenced in this test.
51 * @var \Drupal\Core\Entity\EntityInterface
53 protected $referencedEntity;
56 * The entity that is not yet saved to its persistent storage to be referenced
59 * @var \Drupal\Core\Entity\EntityInterface
61 protected $unsavedReferencedEntity;
63 protected function setUp() {
66 // Use Classy theme for testing markup output.
67 \Drupal::service('theme_handler')->install(['classy']);
68 $this->config('system.theme')->set('default', 'classy')->save();
69 $this->installEntitySchema('entity_test');
70 // Grant the 'view test entity' permission.
71 $this->installConfig(['user']);
72 Role::load(RoleInterface::ANONYMOUS_ID)
73 ->grantPermission('view test entity')
76 // The label formatter rendering generates links, so build the router.
77 $this->container->get('router.builder')->rebuild();
79 $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
81 // Set up a field, so that the entity that'll be referenced bubbles up a
82 // cache tag when rendering it entirely.
83 FieldStorageConfig::create([
84 'field_name' => 'body',
85 'entity_type' => $this->entityType,
90 'entity_type' => $this->entityType,
91 'bundle' => $this->bundle,
92 'field_name' => 'body',
95 entity_get_display($this->entityType, $this->bundle, 'default')
96 ->setComponent('body', [
97 'type' => 'text_default',
102 FilterFormat::create([
103 'format' => 'full_html',
104 'name' => 'Full HTML',
107 // Create the entity to be referenced.
108 $this->referencedEntity = $this->container->get('entity_type.manager')
109 ->getStorage($this->entityType)
110 ->create(['name' => $this->randomMachineName()]);
111 $this->referencedEntity->body = [
112 'value' => '<p>Hello, world!</p>',
113 'format' => 'full_html',
115 $this->referencedEntity->save();
117 // Create another entity to be referenced but do not save it.
118 $this->unsavedReferencedEntity = $this->container->get('entity_type.manager')
119 ->getStorage($this->entityType)
120 ->create(['name' => $this->randomMachineName()]);
121 $this->unsavedReferencedEntity->body = [
122 'value' => '<p>Hello, unsaved world!</p>',
123 'format' => 'full_html',
128 * Assert inaccessible items don't change the data of the fields.
130 public function testAccess() {
131 // Revoke the 'view test entity' permission for this test.
132 Role::load(RoleInterface::ANONYMOUS_ID)
133 ->revokePermission('view test entity')
136 $field_name = $this->fieldName;
138 $referencing_entity = $this->container->get('entity_type.manager')
139 ->getStorage($this->entityType)
140 ->create(['name' => $this->randomMachineName()]);
141 $referencing_entity->save();
142 $referencing_entity->{$field_name}->entity = $this->referencedEntity;
144 // Assert user doesn't have access to the entity.
145 $this->assertFalse($this->referencedEntity->access('view'), 'Current user does not have access to view the referenced entity.');
147 $formatter_manager = $this->container->get('plugin.manager.field.formatter');
149 // Get all the existing formatters.
150 foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) {
151 // Set formatter type for the 'full' view mode.
152 entity_get_display($this->entityType, $this->bundle, 'default')
153 ->setComponent($field_name, [
154 'type' => $formatter,
158 // Invoke entity view.
159 entity_view($referencing_entity, 'default');
161 // Verify the un-accessible item still exists.
162 $this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', ['@name' => $name]));
167 * Tests the merging of cache metadata.
169 public function testCustomCacheTagFormatter() {
170 /** @var \Drupal\Core\Render\RendererInterface $renderer */
171 $renderer = $this->container->get('renderer');
172 $formatter = 'entity_reference_custom_cache_tag';
173 $build = $this->buildRenderArray([$this->referencedEntity], $formatter);
175 $renderer->renderRoot($build);
176 $this->assertTrue(in_array('custom_cache_tag', $build['#cache']['tags']));
180 * Tests the ID formatter.
182 public function testIdFormatter() {
183 $formatter = 'entity_reference_entity_id';
184 $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
186 $this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->id(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
187 $this->assertEqual($build[0]['#cache']['tags'], $this->referencedEntity->getCacheTags(), sprintf('The %s formatter has the expected cache tags.', $formatter));
188 $this->assertTrue(!isset($build[1]), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
192 * Tests the entity formatter.
194 public function testEntityFormatter() {
195 /** @var \Drupal\Core\Render\RendererInterface $renderer */
196 $renderer = $this->container->get('renderer');
197 $formatter = 'entity_reference_entity_view';
198 $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
200 // Test the first field item.
201 $expected_rendered_name_field_1 = '
202 <div class="field field--name-name field--type-string field--label-hidden field__item">' . $this->referencedEntity->label() . '</div>
204 $expected_rendered_body_field_1 = '
205 <div class="clearfix text-formatted field field--name-body field--type-text field--label-above">
206 <div class="field__label">Body</div>
207 <div class="field__item"><p>Hello, world!</p></div>
210 $renderer->renderRoot($build[0]);
211 $this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field_1 . $expected_rendered_body_field_1, sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
212 $expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTags(), $this->referencedEntity->getCacheTags());
213 $expected_cache_tags = Cache::mergeTags($expected_cache_tags, FilterFormat::load('full_html')->getCacheTags());
214 $this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', ['@formatter' => $formatter]));
216 // Test the second field item.
217 $expected_rendered_name_field_2 = '
218 <div class="field field--name-name field--type-string field--label-hidden field__item">' . $this->unsavedReferencedEntity->label() . '</div>
220 $expected_rendered_body_field_2 = '
221 <div class="clearfix text-formatted field field--name-body field--type-text field--label-above">
222 <div class="field__label">Body</div>
223 <div class="field__item"><p>Hello, unsaved world!</p></div>
227 $renderer->renderRoot($build[1]);
228 $this->assertEqual($build[1]['#markup'], 'default | ' . $this->unsavedReferencedEntity->label() . $expected_rendered_name_field_2 . $expected_rendered_body_field_2, sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
232 * Tests the recursive rendering protection of the entity formatter.
234 public function testEntityFormatterRecursiveRendering() {
235 /** @var \Drupal\Core\Render\RendererInterface $renderer */
236 $renderer = $this->container->get('renderer');
237 $formatter = 'entity_reference_entity_view';
238 $view_builder = $this->entityManager->getViewBuilder($this->entityType);
240 // Set the default view mode to use the 'entity_reference_entity_view'
242 entity_get_display($this->entityType, $this->bundle, 'default')
243 ->setComponent($this->fieldName, [
244 'type' => $formatter,
248 $referencing_entity_1 = entity_create($this->entityType, ['name' => $this->randomMachineName()]);
249 $referencing_entity_1->save();
251 // Create a self-reference.
252 $referencing_entity_1->{$this->fieldName}->entity = $referencing_entity_1;
253 $referencing_entity_1->save();
255 // Check that the recursive rendering stops after it reaches the specified
257 $build = $view_builder->view($referencing_entity_1, 'default');
258 $output = $renderer->renderRoot($build);
260 // The title of entity_test entities is printed twice by default, so we have
261 // to multiply the formatter's recursive rendering protection limit by 2.
262 // Additionally, we have to take into account 2 additional occurrences of
263 // the entity title because we're rendering the full entity, not just the
265 $expected_occurrences = EntityReferenceEntityFormatter::RECURSIVE_RENDER_LIMIT * 2 + 2;
266 $actual_occurrences = substr_count($output, $referencing_entity_1->name->value);
267 $this->assertEqual($actual_occurrences, $expected_occurrences);
269 // Repeat the process with another entity in order to check that the
270 // 'recursive_render_id' counter is generated properly.
271 $referencing_entity_2 = entity_create($this->entityType, ['name' => $this->randomMachineName()]);
272 $referencing_entity_2->save();
273 $referencing_entity_2->{$this->fieldName}->entity = $referencing_entity_2;
274 $referencing_entity_2->save();
276 $build = $view_builder->view($referencing_entity_2, 'default');
277 $output = $renderer->renderRoot($build);
279 $actual_occurrences = substr_count($output, $referencing_entity_2->name->value);
280 $this->assertEqual($actual_occurrences, $expected_occurrences);
282 // Now render both entities at the same time and check again.
283 $build = $view_builder->viewMultiple([$referencing_entity_1, $referencing_entity_2], 'default');
284 $output = $renderer->renderRoot($build);
286 $actual_occurrences = substr_count($output, $referencing_entity_1->name->value);
287 $this->assertEqual($actual_occurrences, $expected_occurrences);
289 $actual_occurrences = substr_count($output, $referencing_entity_2->name->value);
290 $this->assertEqual($actual_occurrences, $expected_occurrences);
294 * Renders the same entity referenced from different places.
296 public function testEntityReferenceRecursiveProtectionWithManyRenderedEntities() {
297 $formatter = 'entity_reference_entity_view';
298 $view_builder = $this->entityManager->getViewBuilder($this->entityType);
300 // Set the default view mode to use the 'entity_reference_entity_view'
302 entity_get_display($this->entityType, $this->bundle, 'default')
303 ->setComponent($this->fieldName, [
304 'type' => $formatter,
308 $storage = $this->entityManager->getStorage($this->entityType);
309 /** @var \Drupal\Core\Entity\ContentEntityInterface $referenced_entity */
310 $referenced_entity = $storage->create(['name' => $this->randomMachineName()]);
312 $range = range(0, 30);
313 $referencing_entities = array_map(function () use ($storage, $referenced_entity) {
314 $referencing_entity = $storage->create([
315 'name' => $this->randomMachineName(),
316 $this->fieldName => $referenced_entity,
318 $referencing_entity->save();
319 return $referencing_entity;
322 $build = $view_builder->viewMultiple($referencing_entities, 'default');
323 $output = $this->render($build);
325 // The title of entity_test entities is printed twice by default, so we have
326 // to multiply the formatter's recursive rendering protection limit by 2.
327 // Additionally, we have to take into account 2 additional occurrences of
328 // the entity title because we're rendering the full entity, not just the
330 $expected_occurrences = 30 * 2 + 2;
331 $actual_occurrences = substr_count($output, $referenced_entity->get('name')->value);
332 $this->assertEquals($expected_occurrences, $actual_occurrences);
337 * Tests the label formatter.
339 public function testLabelFormatter() {
340 $this->installEntitySchema('entity_test_label');
341 /** @var \Drupal\Core\Render\RendererInterface $renderer */
342 $renderer = $this->container->get('renderer');
343 $formatter = 'entity_reference_label';
345 // The 'link' settings is TRUE by default.
346 $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
348 $expected_field_cacheability = [
351 'max-age' => Cache::PERMANENT,
353 $this->assertEqual($build['#cache'], $expected_field_cacheability, 'The field render array contains the entity access cacheability metadata');
356 '#title' => $this->referencedEntity->label(),
357 '#url' => $this->referencedEntity->urlInfo(),
358 '#options' => $this->referencedEntity->urlInfo()->getOptions(),
363 'tags' => $this->referencedEntity->getCacheTags(),
366 $this->assertEqual($renderer->renderRoot($build[0]), $renderer->renderRoot($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
367 $this->assertEqual(CacheableMetadata::createFromRenderArray($build[0]), CacheableMetadata::createFromRenderArray($expected_item_1));
369 // The second referenced entity is "autocreated", therefore not saved and
370 // lacking any URL info.
372 '#plain_text' => $this->unsavedReferencedEntity->label(),
377 'tags' => $this->unsavedReferencedEntity->getCacheTags(),
378 'max-age' => Cache::PERMANENT,
381 $this->assertEqual($build[1], $expected_item_2, sprintf('The render array returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
383 // Test with the 'link' setting set to FALSE.
384 $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, ['link' => FALSE]);
385 $this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
386 $this->assertEqual($build[1]['#plain_text'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
388 // Test an entity type that doesn't have any link templates, which means
389 // \Drupal\Core\Entity\EntityInterface::urlInfo() will throw an exception
390 // and the label formatter will output only the label instead of a link.
391 $field_storage_config = FieldStorageConfig::loadByName($this->entityType, $this->fieldName);
392 $field_storage_config->setSetting('target_type', 'entity_test_label');
393 $field_storage_config->save();
395 $referenced_entity_with_no_link_template = EntityTestLabel::create([
396 'name' => $this->randomMachineName(),
398 $referenced_entity_with_no_link_template->save();
400 $build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, ['link' => TRUE]);
401 $this->assertEqual($build[0]['#plain_text'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter));
405 * Sets field values and returns a render array as built by
406 * \Drupal\Core\Field\FieldItemListInterface::view().
408 * @param \Drupal\Core\Entity\EntityInterface[] $referenced_entities
409 * An array of entity objects that will be referenced.
410 * @param string $formatter
411 * The formatted plugin that will be used for building the render array.
412 * @param array $formatter_options
413 * Settings specific to the formatter. Defaults to the formatter's default
419 protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = []) {
420 // Create the entity that will have the entity reference field.
421 $referencing_entity = $this->container->get('entity_type.manager')
422 ->getStorage($this->entityType)
423 ->create(['name' => $this->randomMachineName()]);
425 $items = $referencing_entity->get($this->fieldName);
427 // Assign the referenced entities.
428 foreach ($referenced_entities as $referenced_entity) {
429 $items[] = ['entity' => $referenced_entity];
432 // Build the renderable array for the field.
433 return $items->view(['type' => $formatter, 'settings' => $formatter_options]);