Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / field / src / Tests / EntityReference / EntityReferenceAdminTest.php
1 <?php
2
3 namespace Drupal\field\Tests\EntityReference;
4
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;
12
13 /**
14  * Tests for the administrative UI.
15  *
16  * @group entity_reference
17  */
18 class EntityReferenceAdminTest extends WebTestBase {
19
20   use FieldUiTestTrait;
21
22   /**
23    * Modules to install.
24    *
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.
28    *
29    * @var array
30    */
31   public static $modules = ['node', 'field_ui', 'path', 'taxonomy', 'block', 'views_ui'];
32
33   /**
34    * The name of the content type created for testing purposes.
35    *
36    * @var string
37    */
38   protected $type;
39
40   /**
41    * {@inheritdoc}
42    */
43   protected function setUp() {
44     parent::setUp();
45     $this->drupalPlaceBlock('system_breadcrumb_block');
46
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();
51
52     // Create test user.
53     $admin_user = $this->drupalCreateUser([
54       'access content',
55       'administer node fields',
56       'administer node display',
57       'administer views',
58       'create ' . $type_name . ' content',
59       'edit own ' . $type_name . ' content',
60     ]);
61     $this->drupalLogin($admin_user);
62   }
63
64   /**
65    * Tests the Entity Reference Admin UI.
66    */
67   public function testFieldAdminHandler() {
68     $bundle_path = 'admin/structure/types/manage/' . $this->type;
69
70     // First step: 'Add new field' on the 'Manage fields' page.
71     $this->drupalGet($bundle_path . '/fields/add-field');
72
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');
76
77     $this->drupalPostForm(NULL, [
78       'label' => 'Test label',
79       'field_name' => 'test',
80       'new_storage_type' => 'entity_reference',
81     ], t('Save and continue'));
82
83     // Node should be selected by default.
84     $this->assertFieldByName('settings[target_type]', 'node');
85
86     // Check that all entity types can be referenced.
87     $this->assertFieldSelectOptions('settings[target_type]', array_keys(\Drupal::entityManager()->getDefinitions()));
88
89     // Second step: 'Field settings' form.
90     $this->drupalPostForm(NULL, [], t('Save field settings'));
91
92     // The base handler should be selected by default.
93     $this->assertFieldByName('settings[handler]', 'default:node');
94
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 . ']');
102     }
103
104     reset($bundles);
105
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');
113
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']");
120
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]');
124
125     // Third step: confirm.
126     $this->drupalPostForm(NULL, [
127       'required' => '1',
128       'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
129     ], t('Save settings'));
130
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.');
133
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'));
139
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';
143     $edit = [
144       'settings[target_type]' => 'taxonomy_term',
145     ];
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]');
149
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';
153     $edit = [
154       'settings[target_type]' => 'user',
155     ];
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');
159
160     // Switch the target type to 'node'.
161     $field_name = 'node.' . $this->type . '.field_test';
162     $edit = [
163       'settings[target_type]' => 'node',
164     ];
165     $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
166
167     // Try to select the views handler.
168     $edit = [
169       'settings[handler]' => 'views',
170     ];
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'),
175     ]));
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.');
179
180     // Enable the entity_reference_test module which creates an eligible view.
181     $this->container->get('module_installer')->install(['entity_reference_test']);
182     $this->resetAll();
183     $this->drupalGet($bundle_path . '/fields/' . $field_name);
184     $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
185     $edit = [
186       'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
187     ];
188     $this->drupalPostForm(NULL, $edit, t('Save settings'));
189     $this->assertResponse(200);
190
191     // Switch the target type to 'entity_test'.
192     $edit = [
193       'settings[target_type]' => 'entity_test',
194     ];
195     $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
196     $this->drupalGet($bundle_path . '/fields/' . $field_name);
197     $edit = [
198       'settings[handler]' => 'views',
199     ];
200     $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
201     $edit = [
202       'required' => FALSE,
203       'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
204     ];
205     $this->drupalPostForm(NULL, $edit, t('Save settings'));
206     $this->assertResponse(200);
207
208     // Create a new view and display it as a entity reference.
209     $edit = [
210       'id' => 'node_test_view',
211       'label' => 'Node Test View',
212       'show[wizard_key]' => 'node',
213       'show[sort]' => 'none',
214       'page[create]' => 1,
215       'page[title]' => 'Test Node View',
216       'page[path]' => 'test/node/view',
217       'page[style][style_plugin]' => 'default',
218       'page[style][row_plugin]' => 'fields',
219     ];
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'));
223     $edit = [
224       'style_options[search_fields][title]' => 'title',
225     ];
226     $this->drupalPostForm(NULL, $edit, t('Apply'));
227
228     // Set sort to NID ascending.
229     $edit = [
230       'name[node_field_data.nid]' => 1,
231     ];
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'));
234
235     $this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
236     $this->clickLink(t('Settings'));
237
238     // Create a test entity reference field.
239     $field_name = 'test_entity_ref_field';
240     $edit = [
241       'new_storage_type' => 'field_ui:entity_reference:node',
242       'label' => 'Test Entity Reference Field',
243       'field_name' => $field_name,
244     ];
245     $this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
246
247     // Set to unlimited.
248     $edit = [
249       'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
250     ];
251     $this->drupalPostForm(NULL, $edit, t('Save field settings'));
252
253     // Add the view to the test field.
254     $edit = [
255       'settings[handler]' => 'views',
256     ];
257     $this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
258     $edit = [
259       'required' => FALSE,
260       'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
261     ];
262     $this->drupalPostForm(NULL, $edit, t('Save settings'));
263
264     // Create nodes.
265     $node1 = Node::create([
266       'type' => $this->type,
267       'title' => 'Foo Node',
268     ]);
269     $node1->save();
270     $node2 = Node::create([
271       'type' => $this->type,
272       'title' => 'Foo Node',
273     ]);
274     $node2->save();
275
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() . ')');
283
284     // Try to add a new node, fill the entity reference field and submit the
285     // form.
286     $this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
287     $edit = [
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() . ')',
291     ];
292     $this->drupalPostForm(NULL, $edit, t('Save'));
293     $this->assertResponse(200);
294
295     $edit = [
296       'title[0][value]' => 'Example',
297       'field_test_entity_ref_field[0][target_id]' => 'Test'
298     ];
299     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
300
301     // Assert that entity reference autocomplete field is validated.
302     $this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
303
304     $edit = [
305       'title[0][value]' => 'Test',
306       'field_test_entity_ref_field[0][target_id]' => $node1->getTitle()
307     ];
308     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
309
310     // Assert the results multiple times to avoid sorting problem of nodes with
311     // the same title.
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() . ')']));
316
317     $edit = [
318       'title[0][value]' => 'Test',
319       'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')'
320     ];
321     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
322     $this->assertLink($node1->getTitle());
323
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');
329     $edit = [
330       'cardinality' => -1,
331     ];
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')
338       ->accessCheck(FALSE)
339       ->execute();
340     $this->assertIdentical(0, count($result), "No taxonomy terms exist with the name '$term_name'.");
341     $edit = [
342       // This must be set before new entities will be auto-created.
343       'settings[handler_settings][auto_create]' => 1,
344     ];
345     $this->drupalPostForm(NULL, $edit, t('Save settings'));
346     $this->drupalGet($bundle_path . '/fields/' . $field_path);
347     $edit = [
348       // A term that doesn't yet exist.
349       'default_value_input[field_' . $taxonomy_term_field_name . '][0][target_id]' => $term_name,
350     ];
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')
356       ->accessCheck(FALSE)
357       ->execute();
358     $this->assertIdentical(1, count($result), 'Taxonomy term was auto created when set as field default.');
359   }
360
361   /**
362    * Tests the formatters for the Entity References.
363    */
364   public function testAvailableFormatters() {
365     // Create a new vocabulary.
366     Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
367
368     // Create entity reference field with taxonomy term as a target.
369     $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
370
371     // Create entity reference field with user as a target.
372     $user_field_name = $this->createEntityReferenceField('user');
373
374     // Create entity reference field with node as a target.
375     $node_field_name = $this->createEntityReferenceField('node', [$this->type]);
376
377     // Create entity reference field with date format as a target.
378     $date_format_field_name = $this->createEntityReferenceField('date_format');
379
380     // Display all newly created Entity Reference configuration.
381     $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display');
382
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',
390     ]);
391
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]', [
396       'author',
397       'entity_reference_entity_id',
398       'entity_reference_entity_view',
399       'entity_reference_label',
400     ]);
401
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',
408     ]);
409
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',
416     ]);
417   }
418
419   /**
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.
422    */
423   public function testMultipleTargetBundles() {
424     /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
425     $vocabularies = [];
426     for ($i = 0; $i < 2; $i++) {
427       $vid = Unicode::strtolower($this->randomMachineName());
428       $vocabularies[$i] = Vocabulary::create([
429         'name' => $this->randomString(),
430         'vid' => $vid,
431       ]);
432       $vocabularies[$i]->save();
433     }
434
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;
440
441     $this->drupalGet($path);
442
443     // Expect that there's no 'auto_create_bundle' selected.
444     $this->assertNoFieldByName('settings[handler_settings][auto_create_bundle]');
445
446     $edit = [
447       'settings[handler_settings][target_bundles][' . $vocabularies[1]->id() . ']' => TRUE,
448     ];
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() . "']");
454
455     $edit = [
456       'settings[handler_settings][auto_create]' => TRUE,
457       'settings[handler_settings][auto_create_bundle]' => $vocabularies[1]->id(),
458     ];
459     $this->drupalPostForm(NULL, $edit, t('Save settings'));
460
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());
465
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());
471
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']));
478   }
479
480   /**
481    * Creates a new Entity Reference fields with a given target type.
482    *
483    * @param string $target_type
484    *   The name of the target type
485    * @param string[] $bundles
486    *   A list of bundle IDs. Defaults to [].
487    *
488    * @return string
489    *   Returns the generated field name
490    */
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;
494
495     // Generate a random field name, must be only lowercase characters.
496     $field_name = strtolower($this->randomMachineName());
497
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;
502     }
503
504     $this->fieldUIAddNewField($bundle_path, $field_name, NULL, 'entity_reference', $storage_edit, $field_edit);
505
506     // Returns the generated field name.
507     return $field_name;
508   }
509
510   /**
511    * Checks if a select element contains the specified options.
512    *
513    * @param string $name
514    *   The field name.
515    * @param array $expected_options
516    *   An array of expected options.
517    *
518    * @return bool
519    *   TRUE if the assertion succeeded, FALSE otherwise.
520    */
521   protected function assertFieldSelectOptions($name, array $expected_options) {
522     $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
523     $fields = $this->xpath($xpath);
524     if ($fields) {
525       $field = $fields[0];
526       $options = $this->getAllOptionsList($field);
527
528       sort($options);
529       sort($expected_options);
530
531       return $this->assertIdentical($options, $expected_options);
532     }
533     else {
534       return $this->fail('Unable to find field ' . $name);
535     }
536   }
537
538   /**
539    * Extracts all options from a select element.
540    *
541    * @param \SimpleXMLElement $element
542    *   The select element field information.
543    *
544    * @return array
545    *   An array of option values as strings.
546    */
547   protected function getAllOptionsList(\SimpleXMLElement $element) {
548     $options = [];
549     // Add all options items.
550     foreach ($element->option as $option) {
551       $options[] = (string) $option['value'];
552     }
553
554     // Loops trough all the option groups
555     foreach ($element->optgroup as $optgroup) {
556       $options = array_merge($this->getAllOptionsList($optgroup), $options);
557     }
558
559     return $options;
560   }
561
562 }