Security update for Core, with self-updated composer
[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     $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 . ']');
100     }
101
102     reset($bundles);
103
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');
111
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']");
118
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]');
122
123     // Third step: confirm.
124     $this->drupalPostForm(NULL, [
125       'required' => '1',
126       'settings[handler_settings][target_bundles][' . key($bundles) . ']' => key($bundles),
127     ], t('Save settings'));
128
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.');
131
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'));
137
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';
141     $edit = [
142       'settings[target_type]' => 'taxonomy_term',
143     ];
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]');
147
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';
151     $edit = [
152       'settings[target_type]' => 'user',
153     ];
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');
157
158     // Switch the target type to 'node'.
159     $field_name = 'node.' . $this->type . '.field_test';
160     $edit = [
161       'settings[target_type]' => 'node',
162     ];
163     $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
164
165     // Try to select the views handler.
166     $edit = [
167       'settings[handler]' => 'views',
168     ];
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'),
173     ]));
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.');
177
178     // Enable the entity_reference_test module which creates an eligible view.
179     $this->container->get('module_installer')->install(['entity_reference_test']);
180     $this->resetAll();
181     $this->drupalGet($bundle_path . '/fields/' . $field_name);
182     $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
183     $edit = [
184       'settings[handler_settings][view][view_and_display]' => 'test_entity_reference:entity_reference_1',
185     ];
186     $this->drupalPostForm(NULL, $edit, t('Save settings'));
187     $this->assertResponse(200);
188
189     // Switch the target type to 'entity_test'.
190     $edit = [
191       'settings[target_type]' => 'entity_test',
192     ];
193     $this->drupalPostForm($bundle_path . '/fields/' . $field_name . '/storage', $edit, t('Save field settings'));
194     $this->drupalGet($bundle_path . '/fields/' . $field_name);
195     $edit = [
196       'settings[handler]' => 'views',
197     ];
198     $this->drupalPostAjaxForm($bundle_path . '/fields/' . $field_name, $edit, 'settings[handler]');
199     $edit = [
200       'required' => FALSE,
201       'settings[handler_settings][view][view_and_display]' => 'test_entity_reference_entity_test:entity_reference_1',
202     ];
203     $this->drupalPostForm(NULL, $edit, t('Save settings'));
204     $this->assertResponse(200);
205
206     // Create a new view and display it as a entity reference.
207     $edit = [
208       'id' => 'node_test_view',
209       'label' => 'Node Test View',
210       'show[wizard_key]' => 'node',
211       'show[sort]' => 'none',
212       'page[create]' => 1,
213       'page[title]' => 'Test Node View',
214       'page[path]' => 'test/node/view',
215       'page[style][style_plugin]' => 'default',
216       'page[style][row_plugin]' => 'fields',
217     ];
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'));
221     $edit = [
222       'style_options[search_fields][title]' => 'title',
223     ];
224     $this->drupalPostForm(NULL, $edit, t('Apply'));
225
226     // Set sort to NID ascending.
227     $edit = [
228       'name[node_field_data.nid]' => 1,
229     ];
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'));
232
233     $this->drupalPostForm('admin/structure/views/view/node_test_view/edit/entity_reference_1', [], t('Save'));
234     $this->clickLink(t('Settings'));
235
236     // Create a test entity reference field.
237     $field_name = 'test_entity_ref_field';
238     $edit = [
239       'new_storage_type' => 'field_ui:entity_reference:node',
240       'label' => 'Test Entity Reference Field',
241       'field_name' => $field_name,
242     ];
243     $this->drupalPostForm($bundle_path . '/fields/add-field', $edit, t('Save and continue'));
244
245     // Set to unlimited.
246     $edit = [
247       'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
248     ];
249     $this->drupalPostForm(NULL, $edit, t('Save field settings'));
250
251     // Add the view to the test field.
252     $edit = [
253       'settings[handler]' => 'views',
254     ];
255     $this->drupalPostAjaxForm(NULL, $edit, 'settings[handler]');
256     $edit = [
257       'required' => FALSE,
258       'settings[handler_settings][view][view_and_display]' => 'node_test_view:entity_reference_1',
259     ];
260     $this->drupalPostForm(NULL, $edit, t('Save settings'));
261
262     // Create nodes.
263     $node1 = Node::create([
264       'type' => $this->type,
265       'title' => 'Foo Node',
266     ]);
267     $node1->save();
268     $node2 = Node::create([
269       'type' => $this->type,
270       'title' => 'Foo Node',
271     ]);
272     $node2->save();
273
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() . ')');
281
282     // Try to add a new node, fill the entity reference field and submit the
283     // form.
284     $this->drupalPostForm('node/add/' . $this->type, [], t('Add another item'));
285     $edit = [
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() . ')',
289     ];
290     $this->drupalPostForm(NULL, $edit, t('Save'));
291     $this->assertResponse(200);
292
293     $edit = [
294       'title[0][value]' => 'Example',
295       'field_test_entity_ref_field[0][target_id]' => 'Test'
296     ];
297     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
298
299     // Assert that entity reference autocomplete field is validated.
300     $this->assertText(t('There are no entities matching "@entity"', ['@entity' => 'Test']));
301
302     $edit = [
303       'title[0][value]' => 'Test',
304       'field_test_entity_ref_field[0][target_id]' => $node1->getTitle()
305     ];
306     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
307
308     // Assert the results multiple times to avoid sorting problem of nodes with
309     // the same title.
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() . ')']));
314
315     $edit = [
316       'title[0][value]' => 'Test',
317       'field_test_entity_ref_field[0][target_id]' => $node1->getTitle() . ' (' . $node1->id() . ')'
318     ];
319     $this->drupalPostForm('node/add/' . $this->type, $edit, t('Save'));
320     $this->assertLink($node1->getTitle());
321
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');
327     $edit = [
328       'cardinality' => -1,
329     ];
330     $this->drupalPostForm(NULL, $edit, t('Save field settings'));
331     $this->drupalGet($bundle_path . '/fields/' . $field_path);
332     $term_name = $this->randomString();
333     $result = \Drupal::entityQuery('taxonomy_term')
334       ->condition('name', $term_name)
335       ->condition('vid', 'tags')
336       ->accessCheck(FALSE)
337       ->execute();
338     $this->assertIdentical(0, count($result), "No taxonomy terms exist with the name '$term_name'.");
339     $edit = [
340       // This must be set before new entities will be auto-created.
341       'settings[handler_settings][auto_create]' => 1,
342     ];
343     $this->drupalPostForm(NULL, $edit, t('Save settings'));
344     $this->drupalGet($bundle_path . '/fields/' . $field_path);
345     $edit = [
346       // A term that doesn't yet exist.
347       'default_value_input[field_' . $taxonomy_term_field_name . '][0][target_id]' => $term_name,
348     ];
349     $this->drupalPostForm(NULL, $edit, t('Save settings'));
350     // The term should now exist.
351     $result = \Drupal::entityQuery('taxonomy_term')
352       ->condition('name', $term_name)
353       ->condition('vid', 'tags')
354       ->accessCheck(FALSE)
355       ->execute();
356     $this->assertIdentical(1, count($result), 'Taxonomy term was auto created when set as field default.');
357   }
358
359   /**
360    * Tests the formatters for the Entity References.
361    */
362   public function testAvailableFormatters() {
363     // Create a new vocabulary.
364     Vocabulary::create(['vid' => 'tags', 'name' => 'tags'])->save();
365
366     // Create entity reference field with taxonomy term as a target.
367     $taxonomy_term_field_name = $this->createEntityReferenceField('taxonomy_term', ['tags']);
368
369     // Create entity reference field with user as a target.
370     $user_field_name = $this->createEntityReferenceField('user');
371
372     // Create entity reference field with node as a target.
373     $node_field_name = $this->createEntityReferenceField('node', [$this->type]);
374
375     // Create entity reference field with date format as a target.
376     $date_format_field_name = $this->createEntityReferenceField('date_format');
377
378     // Display all newly created Entity Reference configuration.
379     $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display');
380
381     // Check for Taxonomy Term select box values.
382     // Test if Taxonomy Term Entity Reference Field has the correct formatters.
383     $this->assertFieldSelectOptions('fields[field_' . $taxonomy_term_field_name . '][type]', [
384       'entity_reference_label',
385       'entity_reference_entity_id',
386       'entity_reference_rss_category',
387       'entity_reference_entity_view',
388     ]);
389
390     // Test if User Reference Field has the correct formatters.
391     // Author should be available for this field.
392     // RSS Category should not be available for this field.
393     $this->assertFieldSelectOptions('fields[field_' . $user_field_name . '][type]', [
394       'author',
395       'entity_reference_entity_id',
396       'entity_reference_entity_view',
397       'entity_reference_label',
398     ]);
399
400     // Test if Node Entity Reference Field has the correct formatters.
401     // RSS Category should not be available for this field.
402     $this->assertFieldSelectOptions('fields[field_' . $node_field_name . '][type]', [
403       'entity_reference_label',
404       'entity_reference_entity_id',
405       'entity_reference_entity_view',
406     ]);
407
408     // Test if Date Format Reference Field has the correct formatters.
409     // RSS Category & Entity View should not be available for this field.
410     // This could be any field without a ViewBuilder.
411     $this->assertFieldSelectOptions('fields[field_' . $date_format_field_name . '][type]', [
412       'entity_reference_label',
413       'entity_reference_entity_id',
414     ]);
415   }
416
417   /**
418    * Tests field settings for an entity reference field when the field has
419    * multiple target bundles and is set to auto-create the target entity.
420    */
421   public function testMultipleTargetBundles() {
422     /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
423     $vocabularies = [];
424     for ($i = 0; $i < 2; $i++) {
425       $vid = Unicode::strtolower($this->randomMachineName());
426       $vocabularies[$i] = Vocabulary::create([
427         'name' => $this->randomString(),
428         'vid' => $vid,
429       ]);
430       $vocabularies[$i]->save();
431     }
432
433     // Create a new field pointing to the first vocabulary.
434     $field_name = $this->createEntityReferenceField('taxonomy_term', [$vocabularies[0]->id()]);
435     $field_name = "field_$field_name";
436     $field_id = 'node.' . $this->type . '.' . $field_name;
437     $path = 'admin/structure/types/manage/' . $this->type . '/fields/' . $field_id;
438
439     $this->drupalGet($path);
440
441     // Expect that there's no 'auto_create_bundle' selected.
442     $this->assertNoFieldByName('settings[handler_settings][auto_create_bundle]');
443
444     $edit = [
445       'settings[handler_settings][target_bundles][' . $vocabularies[1]->id() . ']' => TRUE,
446     ];
447     // Enable the second vocabulary as a target bundle.
448     $this->drupalPostAjaxForm($path, $edit, key($edit));
449     // Expect a select element with the two vocabularies as options.
450     $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[0]->id() . "']");
451     $this->assertFieldByXPath("//select[@name='settings[handler_settings][auto_create_bundle]']/option[@value='" . $vocabularies[1]->id() . "']");
452
453     $edit = [
454       'settings[handler_settings][auto_create]' => TRUE,
455       'settings[handler_settings][auto_create_bundle]' => $vocabularies[1]->id(),
456     ];
457     $this->drupalPostForm(NULL, $edit, t('Save settings'));
458
459     /** @var \Drupal\field\Entity\FieldConfig $field_config */
460     $field_config = FieldConfig::load($field_id);
461     // Expect that the target bundle has been saved in the backend.
462     $this->assertEqual($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
463
464     // Delete the other bundle. Field config should not be affected.
465     $vocabularies[0]->delete();
466     $field_config = FieldConfig::load($field_id);
467     $this->assertTrue($field_config->getSetting('handler_settings')['auto_create']);
468     $this->assertIdentical($field_config->getSetting('handler_settings')['auto_create_bundle'], $vocabularies[1]->id());
469
470     // Delete the bundle set for entity auto-creation. Auto-created settings
471     // should be reset (no auto-creation).
472     $vocabularies[1]->delete();
473     $field_config = FieldConfig::load($field_id);
474     $this->assertFalse($field_config->getSetting('handler_settings')['auto_create']);
475     $this->assertFalse(isset($field_config->getSetting('handler_settings')['auto_create_bundle']));
476   }
477
478   /**
479    * Creates a new Entity Reference fields with a given target type.
480    *
481    * @param string $target_type
482    *   The name of the target type
483    * @param string[] $bundles
484    *   A list of bundle IDs. Defaults to [].
485    *
486    * @return string
487    *   Returns the generated field name
488    */
489   protected function createEntityReferenceField($target_type, $bundles = []) {
490     // Generates a bundle path for the newly created content type.
491     $bundle_path = 'admin/structure/types/manage/' . $this->type;
492
493     // Generate a random field name, must be only lowercase characters.
494     $field_name = strtolower($this->randomMachineName());
495
496     $storage_edit = $field_edit = [];
497     $storage_edit['settings[target_type]'] = $target_type;
498     foreach ($bundles as $bundle) {
499       $field_edit['settings[handler_settings][target_bundles][' . $bundle . ']'] = TRUE;
500     }
501
502     $this->fieldUIAddNewField($bundle_path, $field_name, NULL, 'entity_reference', $storage_edit, $field_edit);
503
504     // Returns the generated field name.
505     return $field_name;
506   }
507
508   /**
509    * Checks if a select element contains the specified options.
510    *
511    * @param string $name
512    *   The field name.
513    * @param array $expected_options
514    *   An array of expected options.
515    *
516    * @return bool
517    *   TRUE if the assertion succeeded, FALSE otherwise.
518    */
519   protected function assertFieldSelectOptions($name, array $expected_options) {
520     $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
521     $fields = $this->xpath($xpath);
522     if ($fields) {
523       $field = $fields[0];
524       $options = $this->getAllOptionsList($field);
525
526       sort($options);
527       sort($expected_options);
528
529       return $this->assertIdentical($options, $expected_options);
530     }
531     else {
532       return $this->fail('Unable to find field ' . $name);
533     }
534   }
535
536   /**
537    * Extracts all options from a select element.
538    *
539    * @param \SimpleXMLElement $element
540    *   The select element field information.
541    *
542    * @return array
543    *   An array of option values as strings.
544    */
545   protected function getAllOptionsList(\SimpleXMLElement $element) {
546     $options = [];
547     // Add all options items.
548     foreach ($element->option as $option) {
549       $options[] = (string) $option['value'];
550     }
551
552     // Loops trough all the option groups
553     foreach ($element->optgroup as $optgroup) {
554       $options = array_merge($this->getAllOptionsList($optgroup), $options);
555     }
556
557     return $options;
558   }
559
560 }