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