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 $bundles = $this->container->get('entity_type.bundle.info')->getBundleInfo($entity_type_id);
98 foreach ($bundles as $bundle_name => $bundle_info) {
99 $this->assertFieldByName('settings[handler_settings][target_bundles][' . $bundle_name . ']');
104 // Test the sort settings.
105 // Option 0: no sort.
106 $this->assertFieldByName('settings[handler_settings][sort][field]', '_none');
107 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
108 // Option 1: sort by field.
109 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => 'nid'], 'settings[handler_settings][sort][field]');
110 $this->assertFieldByName('settings[handler_settings][sort][direction]', 'ASC');
112 // Test that a non-translatable base field is a sort option.
113 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='nid']");
114 // Test that a translatable base field is a sort option.
115 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='title']");
116 // Test that a configurable field is a sort option.
117 $this->assertFieldByXPath("//select[@name='settings[handler_settings][sort][field]']/option[@value='body.value']");
119 // Set back to no sort.
120 $this->drupalPostAjaxForm(NULL, ['settings[handler_settings][sort][field]' => '_none'], 'settings[handler_settings][sort][field]');
121 $this->assertNoFieldByName('settings[handler_settings][sort][direction]');
123 // Third step: confirm.
124 $this->drupalPostForm(NULL, [
126 'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
127 ], t('Save settings'));
129 // Check that the field appears in the overview form.
130 $this->assertFieldByXPath('//table[@id="field-overview"]//tr[@id="field-test"]/td[1]', 'Test label', 'Field was created and appears in the overview page.');
132 // Check that the field settings form can be submitted again, even when the
133 // field is required.
134 // The first 'Edit' link is for the Body field.
135 $this->clickLink(t('Edit'), 1);
136 $this->drupalPostForm(NULL, [], t('Save settings'));
138 // Switch the target type to 'taxonomy_term' and check that the settings
139 // specific to its selection handler are displayed.
140 $field_name = 'node.' . $this->type . '.field_test';
142 'settings[target_type]' => 'taxonomy_term',
144 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
145 $this->drupalGet($bundle_path . '/fields/' . $field_name);
146 $this->assertFieldByName('settings[handler_settings][auto_create]');
148 // Switch the target type to 'user' and check that the settings specific to
149 // its selection handler are displayed.
150 $field_name = 'node.' . $this->type . '.field_test';
152 'settings[target_type]' => 'user',
154 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
155 $this->drupalGet($bundle_path . '/fields/' . $field_name);
156 $this->assertFieldByName('settings[handler_settings][filter][type]', '_none');
158 // Switch the target type to 'node'.
159 $field_name = 'node.' . $this->type . '.field_test';
161 'settings[target_type]' => 'node',
163 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
165 // Try to select the views handler.
167 'settings[handler]' => 'views',
169 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
170 $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>.', [
171 ':create' => \Drupal::url('views_ui.add'),
172 ':existing' => \Drupal::url('entity.view.collection'),
174 $this->drupalPostForm(NULL, $edit, t('Save settings'));
175 // If no eligible view is available we should see a message.
176 $this->assertText('The views entity selection mode requires a view.');
178 // Enable the entity_reference_test module which creates an eligible view.
179 $this->container->get('module_installer')->install(['entity_reference_test']);
181 $this->drupalGet($bundle_path . '/fields/' . $field_name);
182 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
184 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
186 $this->drupalPostForm(NULL, $edit, t('Save settings'));
187 $this->assertResponse(200);
189 // Switch the target type to 'entity_test'.
191 'settings[target_type]' => 'entity_test',
193 $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
194 $this->drupalGet($bundle_path . '/fields/' . $field_name);
196 'settings[handler]' => 'views',
198 $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
201 'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
203 $this->drupalPostForm(NULL, $edit, t('Save settings'));
204 $this->assertResponse(200);
206 // Create a new view and display it as a entity reference.
208 'id' => 'node_test_view',
209 'label' => 'Node Test View',
210 'show[wizard_key]' => 'node',
211 'show[sort]' => 'none',
213 'page[title]' => 'Test Node View',
214 'page[path]' => 'test/node/view',
215 'page[style][style_plugin]' => 'default',
216 'page[style][row_plugin]' => 'fields',
218 $this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
219 $this->drupalPostForm(NULL, [], t('Duplicate as Entity Reference'));
220 $this->clickLink(t('Settings'));
222 'style_options[search_fields][title]' => 'title',
224 $this->drupalPostForm(NULL, $edit, t('Apply'));
226 // Set sort to NID ascending.
228 'name[node_field_data.nid]' => 1,
230 $this->drupalPostForm('admin/structure/views/nojs/add-handler/node_test_view/entity_reference_1/sort', $edit, t('Add and configure sort criteria'));
231 $this->drupalPostForm(NULL, NULL, t('Apply'));
233 $this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
234 $this->clickLink(t('Settings'));
236 // Create a test entity reference field.
237 $field_name = 'test_entity_ref_field';
239 'new_storage_type' => 'field_ui:entity_reference:node',
240 'label' => 'Test Entity Reference Field',
241 'field_name' => $field_name,
243 $this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
247 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
249 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
251 // Add the view to the test field.
253 'settings[handler]' => 'views',
255 $this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
258 'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
260 $this->drupalPostForm(NULL, $edit, t('Save settings'));
263 $node1 = Node::create([
264 'type' => $this->type,
265 'title' => 'Foo Node',
268 $node2 = Node::create([
269 'type' => $this->type,
270 'title' => 'Foo Node',
274 // Try to add a new node and fill the entity reference field.
275 $this->drupalGet('node/add/' . $this->type);
276 $result = $this->xpath('//input[@name="field_test_entity_ref_field[0][target_id]" and contains(@data-autocomplete-path, "/entity_reference_autocomplete/node/views/")]');
277 $target_url = $this->getAbsoluteUrl($result[0]['data-autocomplete-path']);
278 $this->drupalGet($target_url, ['query' => ['q' => 'Foo']]);
279 $this->assertRaw($node1->getTitle() . ' (' . $node1->id() . ')');
280 $this->assertRaw($node2->getTitle() . ' (' . $node2->id() . ')');
282 // Try to add a new node, fill the entity reference field and submit the
284 $this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
286 'title[0][value]' => 'Example',
287 'field_test_entity_ref_field[0][target_id]' => 'Foo Node (' . $node1->id() . ')',
288 'field_test_entity_ref_field[1][target_id]' => 'Foo Node (' . $node2->id() . ')',
290 $this->drupalPostForm(NULL, $edit, t('Save'));
291 $this->assertResponse(200);
294 'title[0][value]' => 'Example',
295 'field_test_entity_ref_field[0][target_id]' => 'Test'
297 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
299 // Assert that entity reference autocomplete field is validated.
300 $this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
303 'title[0][value]' => 'Test',
304 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle()
306 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
308 // Assert the results multiple times to avoid sorting problem of nodes with
310 $this->assertText(t('Multiple entities match this reference;'));
311 $this->assertText(t("@node1", ['@node1' => $node1->getTitle() . ' (' . $node1->id() . ')']));
312 $this->assertText(t("@node2", ['@node2' => $node2->getTitle() . ' (' . $node2->id() . ')']));
313 $this->assertText(t('Specify the one you want by appending the id in parentheses, like "@example".', ['@example' => $node2->getTitle() . ' (' . $node2->id() . ')']));
316 'title[0][value]' => 'Test',
317 'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')'
319 $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
320 $this->assertLink($node1->getTitle());
322 // Tests adding default values to autocomplete widgets.
323 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
324 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
325 $field_path = 'node.' . $this->type . '.field_' . $taxonomy_term_field_name;
326 $this->drupalGet($bundle_path . '/fields/' . $field_path . '/storage');
330 $this->drupalPostForm(NULL, $edit, t('Save field settings'));
331 $this->drupalGet($bundle_path . '/fields/' . $field_path);
332 $term_name = $this->randomString();
334 // This must be set before new entities will be auto-created.
335 'settings[handler_settings][auto_create]' => 1,
337 $this->drupalPostForm(NULL, $edit, t('Save settings'));
338 $this->drupalGet($bundle_path . '/fields/' . $field_path);
340 // A term that doesn't yet exist.
341 'default_value_input[field_' . $taxonomy_term_field_name . '][0][target_id]' => $term_name,
343 $this->drupalPostForm(NULL, $edit, t('Save settings'));
344 // The term should now exist.
345 $term = taxonomy_term_load_multiple_by_name($term_name, 'tags')[1];
346 $this->assertIdentical(1, count($term), 'Taxonomy term was auto created when set as field default.');
350 * Tests the formatters for the Entity References.
352 public function testAvailableFormatters() {
353 // Create a new vocabulary.
354 Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
356 // Create entity reference field with taxonomy term as a target.
357 $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
359 // Create entity reference field with user as a target.
360 $user_field_name = $this->createEntityReferenceField('user');
362 // Create entity reference field with node as a target.
363 $node_field_name = $this->createEntityReferenceField('node', [$this->type]);
365 // Create entity reference field with date format as a target.
366 $date_format_field_name = $this->createEntityReferenceField('date_format');
368 // Display all newly created Entity Reference configuration.
369 $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display');
371 // Check for Taxonomy Term select box values.
372 // Test if Taxonomy Term Entity Reference Field has the correct formatters.
373 $this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', [
374 'entity_reference_label',
375 'entity_reference_entity_id',
376 'entity_reference_rss_category',
377 'entity_reference_entity_view',
380 // Test if User Reference Field has the correct formatters.
381 // Author should be available for this field.
382 // RSS Category should not be available for this field.
383 $this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', [
385 'entity_reference_entity_id',
386 'entity_reference_entity_view',
387 'entity_reference_label',
390 // Test if Node Entity Reference Field has the correct formatters.
391 // RSS Category should not be available for this field.
392 $this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', [
393 'entity_reference_label',
394 'entity_reference_entity_id',
395 'entity_reference_entity_view',
398 // Test if Date Format Reference Field has the correct formatters.
399 // RSS Category & Entity View should not be available for this field.
400 // This could be any field without a ViewBuilder.
401 $this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', [
402 'entity_reference_label',
403 'entity_reference_entity_id',
408 * Tests field settings for an entity reference field when the field has
409 * multiple target bundles and is set to auto-create the target entity.
411 public function testMultipleTargetBundles() {
412 /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
414 for ($i = 0; $i < 2; $i++) {
415 $vid = Unicode::strtolower($this->randomMachineName());
416 $vocabularies[$i] = Vocabulary::create([
417 'name' => $this->randomString(),
420 $vocabularies[$i]->save();
423 // Create a new field pointing to the first vocabulary.
424 $field_name = $this->createEntityReferenceField('taxonomy_term', [$vocabularies[0]->id()]);
425 $field_name = "field_$field_name";
426 $field_id = 'node.' . $this->type . '.' . $field_name;
427 $path = 'admin/structure/types/manage/' . $this->type . '/fields/' . $field_id;
429 $this->drupalGet($path);
431 // Expect that there's no 'auto_create_bundle' selected.
432 $this->assertNoFieldByName('settings[handler_settings][auto_create_bundle]');
435 'settings[handler_settings][target_bundles][' . $vocabularies[1]->id() . ']' => TRUE,
437 // Enable the second vocabulary as a target bundle.
438 $this->drupalPostAjaxForm($path, $edit, key($edit));
439 // Expect a select element with the two vocabularies as options.
440 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[0]->id() . "']");
441 $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[1]->id() . "']");
444 'settings[handler_settings][auto_create]' => TRUE,
445 'settings[handler_settings][auto_create_bundle]' => $vocabularies[1]->id(),
447 $this->drupalPostForm(NULL, $edit, t('Save settings'));
449 /** @var \Drupal\field\Entity\FieldConfig $field_config */
450 $field_config = FieldConfig::load($field_id);
451 // Expect that the target bundle has been saved in the backend.
452 $this->assertEqual($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
454 // Delete the other bundle. Field config should not be affected.
455 $vocabularies[0]->delete();
456 $field_config = FieldConfig::load($field_id);
457 $this->assertTrue($field_config->getSetting('handler_settings')['auto_create']);
458 $this->assertIdentical($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
460 // Delete the bundle set for entity auto-creation. Auto-created settings
461 // should be reset (no auto-creation).
462 $vocabularies[1]->delete();
463 $field_config = FieldConfig::load($field_id);
464 $this->assertFalse($field_config->getSetting('handler_settings')['auto_create']);
465 $this->assertFalse(isset($field_config->getSetting('handler_settings')['auto_create_bundle']));
469 * Creates a new Entity Reference fields with a given target type.
471 * @param string $target_type
472 * The name of the target type
473 * @param string[] $bundles
474 * A list of bundle IDs. Defaults to [].
477 * Returns the generated field name
479 protected function createEntityReferenceField($target_type, $bundles = []) {
480 // Generates a bundle path for the newly created content type.
481 $bundle_path = 'admin/structure/types/manage/' . $this->type;
483 // Generate a random field name, must be only lowercase characters.
484 $field_name = strtolower($this->randomMachineName());
486 $storage_edit = $field_edit = [];
487 $storage_edit['settings[target_type]'] = $target_type;
488 foreach ($bundles as $bundle) {
489 $field_edit['settings[handler_settings][target_bundles][' . $bundle . ']'] = TRUE;
492 $this->fieldUIAddNewField($bundle_path, $field_name, NULL, 'entity_reference', $storage_edit, $field_edit);
494 // Returns the generated field name.
499 * Checks if a select element contains the specified options.
501 * @param string $name
503 * @param array $expected_options
504 * An array of expected options.
507 * TRUE if the assertion succeeded, FALSE otherwise.
509 protected function assertFieldSelectOptions($name, array $expected_options) {
510 $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
511 $fields = $this->xpath($xpath);
514 $options = $this->getAllOptionsList($field);
517 sort($expected_options);
519 return $this->assertIdentical($options, $expected_options);
522 return $this->fail('Unable to find field ' . $name);
527 * Extracts all options from a select element.
529 * @param \SimpleXMLElement $element
530 * The select element field information.
533 * An array of option values as strings.
535 protected function getAllOptionsList(\SimpleXMLElement $element) {
537 // Add all options items.
538 foreach ($element->option as $option) {
539 $options[] = (string) $option['value'];
542 // Loops trough all the option groups
543 foreach ($element->optgroup as $optgroup) {
544 $options = array_merge($this->getAllOptionsList($optgroup), $options);