3 namespace Drupal\field\Tests\EntityReference;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\field\Entity\FieldConfig;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\field_ui\Tests\FieldUiTestTrait;
9 use Drupal\node\Entity\Node;
10 use Drupal\simpletest\WebTestBase;
11 use Drupal\taxonomy\Entity\Vocabulary;
14 * Tests for the administrative UI.
16 * @group entity_reference
18 class EntityReferenceAdminTest extends WebTestBase {
25 * Enable path module to ensure that the selection handler does not fail for
26 * entities with a path field.
27 * Enable views_ui module to see the no_view_help text.
31 public static $modules = ['node', 'field_ui', 'path', 'taxonomy', 'block', 'views_ui'];
34 * The name of the content type created for testing purposes.
43 protected function setUp() {
45 $this->drupalPlaceBlock('system_breadcrumb_block');
47 // Create a content type, with underscores.
48 $type_name = strtolower($this->randomMachineName(8)) . '_test';
49 $type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
50 $this->type = $type->id();
53 $admin_user = $this->drupalCreateUser([
55 'administer node fields',
56 'administer node display',
58 'create ' . $type_name . ' content',
59 'edit own ' . $type_name . ' content',
61 $this->drupalLogin($admin_user);
65 * Tests the Entity Reference Admin UI.
67 public function testFieldAdminHandler() {
68 $bundle_path = 'admin/structure/types/manage/' . $this->type;
70 // First step: 'Add new field' on the 'Manage fields' page.
71 $this->drupalGet($bundle_path . '/fields/add-field');
73 // Check if the commonly referenced entity types appear in the list.
74 $this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:node');
75 $this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:user');
77 $this->drupalPostForm(NULL, [
78 'label' => 'Test label',
79 'field_name' => 'test',
80 'new_storage_type' => 'entity_reference',
81 ], t('Save and continue'));
83 // Node should be selected by default.
84 $this->assertFieldByName('settings[target_type]', 'node');
86 // Check that all entity types can be referenced.
87 $this->assertFieldSelectOptions('settings[target_type]', array_keys(\Drupal::entityManager()->getDefinitions()));
89 // Second step: 'Field settings' form.
90 $this->drupalPostForm(NULL, [], t('Save field settings'));
92 // The base handler should be selected by default.
93 $this->assertFieldByName('settings[handler]', 'default:node');
95 // The base handler settings should be displayed.
96 $entity_type_id = 'node';
97 // Check that the type label is correctly displayed.
98 $this->assertText('Content type');
99 $bundles = $this->container->get('entity_type.bundle.info')->getBundleInfo($entity_type_id);
100 foreach ($bundles as $bundle_name => $bundle_info) {
101 $this->assertFieldByName('settings[handler_settings][target_bundles][' . $bundle_name . ']');
106 // Test the sort settings.
107 // Option 0: no sort.
108 $this->assertFieldByName('settings[handler_settings][sort][field]', '_none');
109 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
110 // Option 1: sort by field.
111 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => 'nid'], 'settings[handler_settings][sort][field]');
112 $this->assertFieldByName('settings[handler_settings][sort][direction]', 'ASC');
114 // Test that a non-translatable base field is a sort option.
115 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='nid']");
116 // Test that a translatable base field is a sort option.
117 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='title']");
118 // Test that a configurable field is a sort option.
119 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='body.value']");
121 // Set back to no sort.
122 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => '_none'], 'settings[handler_settings][sort][field]');
123 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
125 // Third step: confirm.
126 $this->drupalPostForm(NULL, [
128 'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
129 ], t('Save settings'));
131 // Check that the field appears in the overview form.
132 $this->assertFieldByXPath('//table[@id="field-overview"]//tr[@id="field-test"]/td[1]', 'Test label', 'Field was created and appears in the overview page.');
134 // Check that the field settings form can be submitted again, even when the
135 // field is required.
136 // The first 'Edit' link is for the Body field.
137 $this->clickLink(t('Edit'), 1);
138 $this->drupalPostForm(NULL, [], t('Save settings'));
140 // Switch the target type to 'taxonomy_term' and check that the settings
141 // specific to its selection handler are displayed.
142 $field_name = 'node.' . $this->type . '.field_test';
144 'settings[target_type]' => 'taxonomy_term',
146 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
147 $this->drupalGet($bundle_path . '/fields/' . $field_name);
148 $this->assertFieldByName('settings[handler_settings][auto_create]');
150 // Switch the target type to 'user' and check that the settings specific to
151 // its selection handler are displayed.
152 $field_name = 'node.' . $this->type . '.field_test';
154 'settings[target_type]' => 'user',
156 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
157 $this->drupalGet($bundle_path . '/fields/' . $field_name);
158 $this->assertFieldByName('settings[handler_settings][filter][type]', '_none');
160 // Switch the target type to 'node'.
161 $field_name = 'node.' . $this->type . '.field_test';
163 'settings[target_type]' => 'node',
165 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
167 // Try to select the views handler.
169 'settings[handler]' => 'views',
171 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
172 $this->assertRaw(t('No eligible views were found. <a href=":create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href=":existing">existing view</a>.', [
173 ':create' => \Drupal::url('views_ui.add'),
174 ':existing' => \Drupal::url('entity.view.collection'),
176 $this->drupalPostForm(NULL, $edit, t('Save settings'));
177 // If no eligible view is available we should see a message.
178 $this->assertText('The views entity selection mode requires a view.');
180 // Enable the entity_reference_test module which creates an eligible view.
181 $this->container->get('module_installer')->install(['entity_reference_test']);
183 $this->drupalGet($bundle_path . '/fields/' . $field_name);
184 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
186 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
188 $this->drupalPostForm(NULL, $edit, t('Save settings'));
189 $this->assertResponse(200);
191 // Switch the target type to 'entity_test'.
193 'settings[target_type]' => 'entity_test',
195 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
196 $this->drupalGet($bundle_path . '/fields/' . $field_name);
198 'settings[handler]' => 'views',
200 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
203 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
205 $this->drupalPostForm(NULL, $edit, t('Save settings'));
206 $this->assertResponse(200);
208 // Create a new view and display it as a entity reference.
210 'id' => 'node_test_view',
211 'label' => 'Node Test View',
212 'show[wizard_key]' => 'node',
213 'show[sort]' => 'none',
215 'page[title]' => 'Test Node View',
216 'page[path]' => 'test/node/view',
217 'page[style][style_plugin]' => 'default',
218 'page[style][row_plugin]' => 'fields',
220 $this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
221 $this->drupalPostForm(NULL, [], t('Duplicate as Entity Reference'));
222 $this->clickLink(t('Settings'));
224 'style_options[search_fields][title]' => 'title',
226 $this->drupalPostForm(NULL, $edit, t('Apply'));
228 // Set sort to NID ascending.
230 'name[node_field_data.nid]' => 1,
232 $this->drupalPostForm('admin/structure/views/nojs/add-handler/node_test_view/entity_reference_1/sort', $edit, t('Add and configure sort criteria'));
233 $this->drupalPostForm(NULL, NULL, t('Apply'));
235 $this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
236 $this->clickLink(t('Settings'));
238 // Create a test entity reference field.
239 $field_name = 'test_entity_ref_field';
241 'new_storage_type' => 'field_ui:entity_reference:node',
242 'label' => 'Test Entity Reference Field',
243 'field_name' => $field_name,
245 $this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
249 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
251 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
253 // Add the view to the test field.
255 'settings[handler]' => 'views',
257 $this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
260 'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
262 $this->drupalPostForm(NULL, $edit, t('Save settings'));
265 $node1 = Node::create([
266 'type' => $this->type,
267 'title' => 'Foo Node',
270 $node2 = Node::create([
271 'type' => $this->type,
272 'title' => 'Foo Node',
276 // Try to add a new node and fill the entity reference field.
277 $this->drupalGet('node/add/' . $this->type);
278 $result = $this->xpath('//input[@name="field_test_entity_ref_field[0][target_id]" and contains(@data-autocomplete-path, "/entity_reference_autocomplete/node/views/")]');
279 $target_url = $this->getAbsoluteUrl($result[0]['data-autocomplete-path']);
280 $this->drupalGet($target_url, ['query' => ['q' => 'Foo']]);
281 $this->assertRaw($node1->getTitle() . ' (' . $node1->id() . ')');
282 $this->assertRaw($node2->getTitle() . ' (' . $node2->id() . ')');
284 // Try to add a new node, fill the entity reference field and submit the
286 $this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
288 'title[0][value]' => 'Example',
289 'field_test_entity_ref_field[0][target_id]' => 'Foo Node (' . $node1->id() . ')',
290 'field_test_entity_ref_field[1][target_id]' => 'Foo Node (' . $node2->id() . ')',
292 $this->drupalPostForm(NULL, $edit, t('Save'));
293 $this->assertResponse(200);
296 'title[0][value]' => 'Example',
297 'field_test_entity_ref_field[0][target_id]' => 'Test'
299 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
301 // Assert that entity reference autocomplete field is validated.
302 $this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
305 'title[0][value]' => 'Test',
306 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle()
308 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
310 // Assert the results multiple times to avoid sorting problem of nodes with
312 $this->assertText(t('Multiple entities match this reference;'));
313 $this->assertText(t("@node1", ['@node1' => $node1->getTitle() . ' (' . $node1->id() . ')']));
314 $this->assertText(t("@node2", ['@node2' => $node2->getTitle() . ' (' . $node2->id() . ')']));
315 $this->assertText(t('Specify the one you want by appending the id in parentheses, like "@example".', ['@example' => $node2->getTitle() . ' (' . $node2->id() . ')']));
318 'title[0][value]' => 'Test',
319 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')'
321 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
322 $this->assertLink($node1->getTitle());
324 // Tests adding default values to autocomplete widgets.
325 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
326 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
327 $field_path = 'node.' . $this->type . '.field_' . $taxonomy_term_field_name;
328 $this->drupalGet($bundle_path . '/fields/' . $field_path . '/storage');
332 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
333 $this->drupalGet($bundle_path . '/fields/' . $field_path);
334 $term_name = $this->randomString();
335 $result = \Drupal::entityQuery('taxonomy_term')
336 ->condition('name', $term_name)
337 ->condition('vid', 'tags')
340 $this->assertIdentical(0, count($result), "No taxonomy terms exist with the name '$term_name'.");
342 // This must be set before new entities will be auto-created.
343 'settings[handler_settings][auto_create]' => 1,
345 $this->drupalPostForm(NULL, $edit, t('Save settings'));
346 $this->drupalGet($bundle_path . '/fields/' . $field_path);
348 // A term that doesn't yet exist.
349 'default_value_input[field_' . $taxonomy_term_field_name . '][0][target_id]' => $term_name,
351 $this->drupalPostForm(NULL, $edit, t('Save settings'));
352 // The term should now exist.
353 $result = \Drupal::entityQuery('taxonomy_term')
354 ->condition('name', $term_name)
355 ->condition('vid', 'tags')
358 $this->assertIdentical(1, count($result), 'Taxonomy term was auto created when set as field default.');
362 * Tests the formatters for the Entity References.
364 public function testAvailableFormatters() {
365 // Create a new vocabulary.
366 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
368 // Create entity reference field with taxonomy term as a target.
369 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
371 // Create entity reference field with user as a target.
372 $user_field_name = $this->createEntityReferenceField('user');
374 // Create entity reference field with node as a target.
375 $node_field_name = $this->createEntityReferenceField('node', [$this->type]);
377 // Create entity reference field with date format as a target.
378 $date_format_field_name = $this->createEntityReferenceField('date_format');
380 // Display all newly created Entity Reference configuration.
381 $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display');
383 // Check for Taxonomy Term select box values.
384 // Test if Taxonomy Term Entity Reference Field has the correct formatters.
385 $this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', [
386 'entity_reference_label',
387 'entity_reference_entity_id',
388 'entity_reference_rss_category',
389 'entity_reference_entity_view',
392 // Test if User Reference Field has the correct formatters.
393 // Author should be available for this field.
394 // RSS Category should not be available for this field.
395 $this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', [
397 'entity_reference_entity_id',
398 'entity_reference_entity_view',
399 'entity_reference_label',
402 // Test if Node Entity Reference Field has the correct formatters.
403 // RSS Category should not be available for this field.
404 $this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', [
405 'entity_reference_label',
406 'entity_reference_entity_id',
407 'entity_reference_entity_view',
410 // Test if Date Format Reference Field has the correct formatters.
411 // RSS Category & Entity View should not be available for this field.
412 // This could be any field without a ViewBuilder.
413 $this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', [
414 'entity_reference_label',
415 'entity_reference_entity_id',
420 * Tests field settings for an entity reference field when the field has
421 * multiple target bundles and is set to auto-create the target entity.
423 public function testMultipleTargetBundles() {
424 /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
426 for ($i = 0; $i < 2; $i++) {
427 $vid = Unicode::strtolower($this->randomMachineName());
428 $vocabularies[$i] = Vocabulary::create([
429 'name' => $this->randomString(),
432 $vocabularies[$i]->save();
435 // Create a new field pointing to the first vocabulary.
436 $field_name = $this->createEntityReferenceField('taxonomy_term', [$vocabularies[0]->id()]);
437 $field_name = "field_$field_name";
438 $field_id = 'node.' . $this->type . '.' . $field_name;
439 $path = 'admin/structure/types/manage/' . $this->type . '/fields/' . $field_id;
441 $this->drupalGet($path);
443 // Expect that there's no 'auto_create_bundle' selected.
444 $this->assertNoFieldByName('settings[handler_settings][auto_create_bundle]');
447 'settings[handler_settings][target_bundles][' . $vocabularies[1]->id() . ']' => TRUE,
449 // Enable the second vocabulary as a target bundle.
450 $this->drupalPostAjaxForm($path, $edit, key($edit));
451 // Expect a select element with the two vocabularies as options.
452 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[0]->id() . "']");
453 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[1]->id() . "']");
456 'settings[handler_settings][auto_create]' => TRUE,
457 'settings[handler_settings][auto_create_bundle]' => $vocabularies[1]->id(),
459 $this->drupalPostForm(NULL, $edit, t('Save settings'));
461 /** @var \Drupal\field\Entity\FieldConfig $field_config */
462 $field_config = FieldConfig::load($field_id);
463 // Expect that the target bundle has been saved in the backend.
464 $this->assertEqual($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
466 // Delete the other bundle. Field config should not be affected.
467 $vocabularies[0]->delete();
468 $field_config = FieldConfig::load($field_id);
469 $this->assertTrue($field_config->getSetting('handler_settings')['auto_create']);
470 $this->assertIdentical($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
472 // Delete the bundle set for entity auto-creation. Auto-created settings
473 // should be reset (no auto-creation).
474 $vocabularies[1]->delete();
475 $field_config = FieldConfig::load($field_id);
476 $this->assertFalse($field_config->getSetting('handler_settings')['auto_create']);
477 $this->assertFalse(isset($field_config->getSetting('handler_settings')['auto_create_bundle']));
481 * Creates a new Entity Reference fields with a given target type.
483 * @param string $target_type
484 * The name of the target type
485 * @param string[] $bundles
486 * A list of bundle IDs. Defaults to [].
489 * Returns the generated field name
491 protected function createEntityReferenceField($target_type, $bundles = []) {
492 // Generates a bundle path for the newly created content type.
493 $bundle_path = 'admin/structure/types/manage/' . $this->type;
495 // Generate a random field name, must be only lowercase characters.
496 $field_name = strtolower($this->randomMachineName());
498 $storage_edit = $field_edit = [];
499 $storage_edit['settings[target_type]'] = $target_type;
500 foreach ($bundles as $bundle) {
501 $field_edit['settings[handler_settings][target_bundles][' . $bundle . ']'] = TRUE;
504 $this->fieldUIAddNewField($bundle_path, $field_name, NULL, 'entity_reference', $storage_edit, $field_edit);
506 // Returns the generated field name.
511 * Checks if a select element contains the specified options.
513 * @param string $name
515 * @param array $expected_options
516 * An array of expected options.
519 * TRUE if the assertion succeeded, FALSE otherwise.
521 protected function assertFieldSelectOptions($name, array $expected_options) {
522 $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
523 $fields = $this->xpath($xpath);
526 $options = $this->getAllOptionsList($field);
529 sort($expected_options);
531 return $this->assertIdentical($options, $expected_options);
534 return $this->fail('Unable to find field ' . $name);
539 * Extracts all options from a select element.
541 * @param \SimpleXMLElement $element
542 * The select element field information.
545 * An array of option values as strings.
547 protected function getAllOptionsList(\SimpleXMLElement $element) {
549 // Add all options items.
550 foreach ($element->option as $option) {
551 $options[] = (string) $option['value'];
554 // Loops trough all the option groups
555 foreach ($element->optgroup as $optgroup) {
556 $options = array_merge($this->getAllOptionsList($optgroup), $options);