3 namespace Drupal\field\Tests\EntityReference;
5 use Drupal\field\Entity\FieldConfig;
6 use Drupal\Core\Field\FieldStorageDefinitionInterface;
7 use Drupal\field_ui\Tests\FieldUiTestTrait;
8 use Drupal\node\Entity\Node;
9 use Drupal\simpletest\WebTestBase;
10 use Drupal\taxonomy\Entity\Vocabulary;
13 * Tests for the administrative UI.
15 * @group entity_reference
17 class EntityReferenceAdminTest extends WebTestBase {
24 * Enable path module to ensure that the selection handler does not fail for
25 * entities with a path field.
26 * Enable views_ui module to see the no_view_help text.
30 public static $modules = ['node', 'field_ui', 'path', 'taxonomy', 'block', 'views_ui'];
33 * The name of the content type created for testing purposes.
42 protected function setUp() {
44 $this->drupalPlaceBlock('system_breadcrumb_block');
46 // Create a content type, with underscores.
47 $type_name = strtolower($this->randomMachineName(8)) . '_test';
48 $type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
49 $this->type = $type->id();
52 $admin_user = $this->drupalCreateUser([
54 'administer node fields',
55 'administer node display',
57 'create ' . $type_name . ' content',
58 'edit own ' . $type_name . ' content',
60 $this->drupalLogin($admin_user);
64 * Tests the Entity Reference Admin UI.
66 public function testFieldAdminHandler() {
67 $bundle_path = 'admin/structure/types/manage/' . $this->type;
69 // First step: 'Add new field' on the 'Manage fields' page.
70 $this->drupalGet($bundle_path . '/fields/add-field');
72 // Check if the commonly referenced entity types appear in the list.
73 $this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:node');
74 $this->assertOption('edit-new-storage-type', 'field_ui:entity_reference:user');
76 $this->drupalPostForm(NULL, [
77 'label' => 'Test label',
78 'field_name' => 'test',
79 'new_storage_type' => 'entity_reference',
80 ], t('Save and continue'));
82 // Node should be selected by default.
83 $this->assertFieldByName('settings[target_type]', 'node');
85 // Check that all entity types can be referenced.
86 $this->assertFieldSelectOptions('settings[target_type]', array_keys(\Drupal::entityManager()->getDefinitions()));
88 // Second step: 'Field settings' form.
89 $this->drupalPostForm(NULL, [], t('Save field settings'));
91 // The base handler should be selected by default.
92 $this->assertFieldByName('settings[handler]', 'default:node');
94 // The base handler settings should be displayed.
95 $entity_type_id = 'node';
96 // Check that the type label is correctly displayed.
97 $this->assertText('Content type');
98 $bundles = $this->container->get('entity_type.bundle.info')->getBundleInfo($entity_type_id);
99 foreach ($bundles as $bundle_name => $bundle_info) {
100 $this->assertFieldByName('settings[handler_settings][target_bundles][' . $bundle_name . ']');
105 // Test the sort settings.
106 // Option 0: no sort.
107 $this->assertFieldByName('settings[handler_settings][sort][field]', '_none');
108 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
109 // Option 1: sort by field.
110 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => 'nid'], 'settings[handler_settings][sort][field]');
111 $this->assertFieldByName('settings[handler_settings][sort][direction]', 'ASC');
113 // Test that a non-translatable base field is a sort option.
114 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='nid']");
115 // Test that a translatable base field is a sort option.
116 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='title']");
117 // Test that a configurable field is a sort option.
118 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='body.value']");
120 // Set back to no sort.
121 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => '_none'], 'settings[handler_settings][sort][field]');
122 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
124 // Third step: confirm.
125 $this->drupalPostForm(NULL, [
127 'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
128 ], t('Save settings'));
130 // Check that the field appears in the overview form.
131 $this->assertFieldByXPath('//table[@id="field-overview"]//tr[@id="field-test"]/td[1]', 'Test label', 'Field was created and appears in the overview page.');
133 // Check that the field settings form can be submitted again, even when the
134 // field is required.
135 // The first 'Edit' link is for the Body field.
136 $this->clickLink(t('Edit'), 1);
137 $this->drupalPostForm(NULL, [], t('Save settings'));
139 // Switch the target type to 'taxonomy_term' and check that the settings
140 // specific to its selection handler are displayed.
141 $field_name = 'node.' . $this->type . '.field_test';
143 'settings[target_type]' => 'taxonomy_term',
145 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
146 $this->drupalGet($bundle_path . '/fields/' . $field_name);
147 $this->assertFieldByName('settings[handler_settings][auto_create]');
149 // Switch the target type to 'user' and check that the settings specific to
150 // its selection handler are displayed.
151 $field_name = 'node.' . $this->type . '.field_test';
153 'settings[target_type]' => 'user',
155 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
156 $this->drupalGet($bundle_path . '/fields/' . $field_name);
157 $this->assertFieldByName('settings[handler_settings][filter][type]', '_none');
159 // Switch the target type to 'node'.
160 $field_name = 'node.' . $this->type . '.field_test';
162 'settings[target_type]' => 'node',
164 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
166 // Try to select the views handler.
168 'settings[handler]' => 'views',
170 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
171 $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>.', [
172 ':create' => \Drupal::url('views_ui.add'),
173 ':existing' => \Drupal::url('entity.view.collection'),
175 $this->drupalPostForm(NULL, $edit, t('Save settings'));
176 // If no eligible view is available we should see a message.
177 $this->assertText('The views entity selection mode requires a view.');
179 // Enable the entity_reference_test module which creates an eligible view.
180 $this->container->get('module_installer')->install(['entity_reference_test']);
182 $this->drupalGet($bundle_path . '/fields/' . $field_name);
183 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
185 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
187 $this->drupalPostForm(NULL, $edit, t('Save settings'));
188 $this->assertResponse(200);
190 // Switch the target type to 'entity_test'.
192 'settings[target_type]' => 'entity_test',
194 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
195 $this->drupalGet($bundle_path . '/fields/' . $field_name);
197 'settings[handler]' => 'views',
199 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
202 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
204 $this->drupalPostForm(NULL, $edit, t('Save settings'));
205 $this->assertResponse(200);
207 // Create a new view and display it as a entity reference.
209 'id' => 'node_test_view',
210 'label' => 'Node Test View',
211 'show[wizard_key]' => 'node',
212 'show[sort]' => 'none',
214 'page[title]' => 'Test Node View',
215 'page[path]' => 'test/node/view',
216 'page[style][style_plugin]' => 'default',
217 'page[style][row_plugin]' => 'fields',
219 $this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
220 $this->drupalPostForm(NULL, [], t('Duplicate as Entity Reference'));
221 $this->clickLink(t('Settings'));
223 'style_options[search_fields][title]' => 'title',
225 $this->drupalPostForm(NULL, $edit, t('Apply'));
227 // Set sort to NID ascending.
229 'name[node_field_data.nid]' => 1,
231 $this->drupalPostForm('admin/structure/views/nojs/add-handler/node_test_view/entity_reference_1/sort', $edit, t('Add and configure sort criteria'));
232 $this->drupalPostForm(NULL, NULL, t('Apply'));
234 $this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
235 $this->clickLink(t('Settings'));
237 // Create a test entity reference field.
238 $field_name = 'test_entity_ref_field';
240 'new_storage_type' => 'field_ui:entity_reference:node',
241 'label' => 'Test Entity Reference Field',
242 'field_name' => $field_name,
244 $this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
248 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
250 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
252 // Add the view to the test field.
254 'settings[handler]' => 'views',
256 $this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
259 'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
261 $this->drupalPostForm(NULL, $edit, t('Save settings'));
264 $node1 = Node::create([
265 'type' => $this->type,
266 'title' => 'Foo Node',
269 $node2 = Node::create([
270 'type' => $this->type,
271 'title' => 'Foo Node',
275 // Try to add a new node and fill the entity reference field.
276 $this->drupalGet('node/add/' . $this->type);
277 $result = $this->xpath('//input[@name="field_test_entity_ref_field[0][target_id]" and contains(@data-autocomplete-path, "/entity_reference_autocomplete/node/views/")]');
278 $target_url = $this->getAbsoluteUrl($result[0]['data-autocomplete-path']);
279 $this->drupalGet($target_url, ['query' => ['q' => 'Foo']]);
280 $this->assertRaw($node1->getTitle() . ' (' . $node1->id() . ')');
281 $this->assertRaw($node2->getTitle() . ' (' . $node2->id() . ')');
283 // Try to add a new node, fill the entity reference field and submit the
285 $this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
287 'title[0][value]' => 'Example',
288 'field_test_entity_ref_field[0][target_id]' => 'Foo Node (' . $node1->id() . ')',
289 'field_test_entity_ref_field[1][target_id]' => 'Foo Node (' . $node2->id() . ')',
291 $this->drupalPostForm(NULL, $edit, t('Save'));
292 $this->assertResponse(200);
295 'title[0][value]' => 'Example',
296 'field_test_entity_ref_field[0][target_id]' => 'Test',
298 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
300 // Assert that entity reference autocomplete field is validated.
301 $this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
304 'title[0][value]' => 'Test',
305 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle(),
307 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
309 // Assert the results multiple times to avoid sorting problem of nodes with
311 $this->assertText(t('Multiple entities match this reference;'));
312 $this->assertText(t("@node1", ['@node1' => $node1->getTitle() . ' (' . $node1->id() . ')']));
313 $this->assertText(t("@node2", ['@node2' => $node2->getTitle() . ' (' . $node2->id() . ')']));
314 $this->assertText(t('Specify the one you want by appending the id in parentheses, like "@example".', ['@example' => $node2->getTitle() . ' (' . $node2->id() . ')']));
317 'title[0][value]' => 'Test',
318 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')',
320 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
321 $this->assertLink($node1->getTitle());
323 // Tests adding default values to autocomplete widgets.
324 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
325 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
326 $field_path = 'node.' . $this->type . '.field_' . $taxonomy_term_field_name;
327 $this->drupalGet($bundle_path . '/fields/' . $field_path . '/storage');
331 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
332 $this->drupalGet($bundle_path . '/fields/' . $field_path);
333 $term_name = $this->randomString();
334 $result = \Drupal::entityQuery('taxonomy_term')
335 ->condition('name', $term_name)
336 ->condition('vid', 'tags')
339 $this->assertIdentical(0, count($result), "No taxonomy terms exist with the name '$term_name'.");
341 // This must be set before new entities will be auto-created.
342 'settings[handler_settings][auto_create]' => 1,
344 $this->drupalPostForm(NULL, $edit, t('Save settings'));
345 $this->drupalGet($bundle_path . '/fields/' . $field_path);
347 // A term that doesn't yet exist.
348 'default_value_input[field_' . $taxonomy_term_field_name . '][0][target_id]' => $term_name,
350 $this->drupalPostForm(NULL, $edit, t('Save settings'));
351 // The term should now exist.
352 $result = \Drupal::entityQuery('taxonomy_term')
353 ->condition('name', $term_name)
354 ->condition('vid', 'tags')
357 $this->assertIdentical(1, count($result), 'Taxonomy term was auto created when set as field default.');
361 * Tests the formatters for the Entity References.
363 public function testAvailableFormatters() {
364 // Create a new vocabulary.
365 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
367 // Create entity reference field with taxonomy term as a target.
368 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
370 // Create entity reference field with user as a target.
371 $user_field_name = $this->createEntityReferenceField('user');
373 // Create entity reference field with node as a target.
374 $node_field_name = $this->createEntityReferenceField('node', [$this->type]);
376 // Create entity reference field with date format as a target.
377 $date_format_field_name = $this->createEntityReferenceField('date_format');
379 // Display all newly created Entity Reference configuration.
380 $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display');
382 // Check for Taxonomy Term select box values.
383 // Test if Taxonomy Term Entity Reference Field has the correct formatters.
384 $this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', [
385 'entity_reference_label',
386 'entity_reference_entity_id',
387 'entity_reference_rss_category',
388 'entity_reference_entity_view',
391 // Test if User Reference Field has the correct formatters.
392 // Author should be available for this field.
393 // RSS Category should not be available for this field.
394 $this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', [
396 'entity_reference_entity_id',
397 'entity_reference_entity_view',
398 'entity_reference_label',
401 // Test if Node Entity Reference Field has the correct formatters.
402 // RSS Category should not be available for this field.
403 $this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', [
404 'entity_reference_label',
405 'entity_reference_entity_id',
406 'entity_reference_entity_view',
409 // Test if Date Format Reference Field has the correct formatters.
410 // RSS Category & Entity View should not be available for this field.
411 // This could be any field without a ViewBuilder.
412 $this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', [
413 'entity_reference_label',
414 'entity_reference_entity_id',
419 * Tests field settings for an entity reference field when the field has
420 * multiple target bundles and is set to auto-create the target entity.
422 public function testMultipleTargetBundles() {
423 /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
425 for ($i = 0; $i < 2; $i++) {
426 $vid = mb_strtolower($this->randomMachineName());
427 $vocabularies[$i] = Vocabulary::create([
428 'name' => $this->randomString(),
431 $vocabularies[$i]->save();
434 // Create a new field pointing to the first vocabulary.
435 $field_name = $this->createEntityReferenceField('taxonomy_term', [$vocabularies[0]->id()]);
436 $field_name = "field_$field_name";
437 $field_id = 'node.' . $this->type . '.' . $field_name;
438 $path = 'admin/structure/types/manage/' . $this->type . '/fields/' . $field_id;
440 $this->drupalGet($path);
442 // Expect that there's no 'auto_create_bundle' selected.
443 $this->assertNoFieldByName('settings[handler_settings][auto_create_bundle]');
446 'settings[handler_settings][target_bundles][' . $vocabularies[1]->id() . ']' => TRUE,
448 // Enable the second vocabulary as a target bundle.
449 $this->drupalPostAjaxForm($path, $edit, key($edit));
450 // Expect a select element with the two vocabularies as options.
451 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[0]->id() . "']");
452 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[1]->id() . "']");
455 'settings[handler_settings][auto_create]' => TRUE,
456 'settings[handler_settings][auto_create_bundle]' => $vocabularies[1]->id(),
458 $this->drupalPostForm(NULL, $edit, t('Save settings'));
460 /** @var \Drupal\field\Entity\FieldConfig $field_config */
461 $field_config = FieldConfig::load($field_id);
462 // Expect that the target bundle has been saved in the backend.
463 $this->assertEqual($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
465 // Delete the other bundle. Field config should not be affected.
466 $vocabularies[0]->delete();
467 $field_config = FieldConfig::load($field_id);
468 $this->assertTrue($field_config->getSetting('handler_settings')['auto_create']);
469 $this->assertIdentical($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
471 // Delete the bundle set for entity auto-creation. Auto-created settings
472 // should be reset (no auto-creation).
473 $vocabularies[1]->delete();
474 $field_config = FieldConfig::load($field_id);
475 $this->assertFalse($field_config->getSetting('handler_settings')['auto_create']);
476 $this->assertFalse(isset($field_config->getSetting('handler_settings')['auto_create_bundle']));
480 * Creates a new Entity Reference fields with a given target type.
482 * @param string $target_type
483 * The name of the target type
484 * @param string[] $bundles
485 * A list of bundle IDs. Defaults to [].
488 * Returns the generated field name
490 protected function createEntityReferenceField($target_type, $bundles = []) {
491 // Generates a bundle path for the newly created content type.
492 $bundle_path = 'admin/structure/types/manage/' . $this->type;
494 // Generate a random field name, must be only lowercase characters.
495 $field_name = strtolower($this->randomMachineName());
497 $storage_edit = $field_edit = [];
498 $storage_edit['settings[target_type]'] = $target_type;
499 foreach ($bundles as $bundle) {
500 $field_edit['settings[handler_settings][target_bundles][' . $bundle . ']'] = TRUE;
503 $this->fieldUIAddNewField($bundle_path, $field_name, NULL, 'entity_reference', $storage_edit, $field_edit);
505 // Returns the generated field name.
510 * Checks if a select element contains the specified options.
512 * @param string $name
514 * @param array $expected_options
515 * An array of expected options.
518 * TRUE if the assertion succeeded, FALSE otherwise.
520 protected function assertFieldSelectOptions($name, array $expected_options) {
521 $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
522 $fields = $this->xpath($xpath);
525 $options = $this->getAllOptionsList($field);
528 sort($expected_options);
530 return $this->assertIdentical($options, $expected_options);
533 return $this->fail('Unable to find field ' . $name);
538 * Extracts all options from a select element.
540 * @param \SimpleXMLElement $element
541 * The select element field information.
544 * An array of option values as strings.
546 protected function getAllOptionsList(\SimpleXMLElement $element) {
548 // Add all options items.
549 foreach ($element->option as $option) {
550 $options[] = (string) $option['value'];
553 // Loops trough all the option groups
554 foreach ($element->optgroup as $optgroup) {
555 $options = array_merge($this->getAllOptionsList($optgroup), $options);