3 namespace Drupal\field_ui\Tests;
5 use Drupal\Core\Entity\Entity\EntityFormDisplay;
6 use Drupal\Core\Entity\Entity\EntityViewDisplay;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Language\LanguageInterface;
9 use Drupal\node\Entity\NodeType;
10 use Drupal\simpletest\WebTestBase;
11 use Drupal\taxonomy\Entity\Vocabulary;
14 * Tests the Field UI "Manage display" and "Manage form display" screens.
18 class ManageDisplayTest extends WebTestBase {
27 public static $modules = ['node', 'field_ui', 'taxonomy', 'search', 'field_test', 'field_third_party_test', 'block'];
32 protected function setUp() {
34 $this->drupalPlaceBlock('system_breadcrumb_block');
35 $this->drupalPlaceBlock('local_tasks_block');
37 // Create a test user.
38 $admin_user = $this->drupalCreateUser(['access content', 'administer content types', 'administer node fields', 'administer node form display', 'administer node display', 'administer taxonomy', 'administer taxonomy_term fields', 'administer taxonomy_term display', 'administer users', 'administer account settings', 'administer user display', 'bypass node access']);
39 $this->drupalLogin($admin_user);
41 // Create content type, with underscores.
42 $type_name = strtolower($this->randomMachineName(8)) . '_test';
43 $type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
44 $this->type = $type->id();
46 // Create a default vocabulary.
47 $vocabulary = Vocabulary::create([
48 'name' => $this->randomMachineName(),
49 'description' => $this->randomMachineName(),
50 'vid' => mb_strtolower($this->randomMachineName()),
51 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
53 'nodes' => ['article' => 'article'],
54 'weight' => mt_rand(0, 10),
57 $this->vocabulary = $vocabulary->id();
61 * Tests formatter settings.
63 public function testFormatterUI() {
64 $manage_fields = 'admin/structure/types/manage/' . $this->type;
65 $manage_display = $manage_fields . '/display';
67 // Create a field, and a node with some data for the field.
68 $this->fieldUIAddNewField($manage_fields, 'test', 'Test field');
70 // Get the display options (formatter and settings) that were automatically
71 // assigned for the 'default' display.
72 $display = entity_get_display('node', $this->type, 'default');
73 $display_options = $display->getComponent('field_test');
74 $format = $display_options['type'];
75 $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
76 $setting_name = key($default_settings);
77 $setting_value = $display_options['settings'][$setting_name];
79 // Display the "Manage display" screen and check that the expected formatter
81 $this->drupalGet($manage_display);
82 $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
83 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
85 // Check whether formatter weights are respected.
86 $result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-fields-field-test-type']);
87 $options = array_map(function ($item) {
88 return (string) $item->attributes()->value[0];
93 'field_empty_setting',
95 'field_test_multiple',
96 'field_test_with_prepare_view',
97 'field_test_applicable',
99 $this->assertEqual($options, $expected_options, 'The expected formatter ordering is respected.');
101 // Ensure that fields can be hidden directly by changing the region.
102 $this->drupalGet($manage_display);
103 $this->assertFieldByName('fields[field_test][region]', 'content');
104 $edit = ['fields[field_test][region]' => 'hidden'];
105 $this->drupalPostForm($manage_display, $edit, t('Save'));
106 $this->assertFieldByName('fields[field_test][region]', 'hidden');
107 $display = EntityViewDisplay::load("node.{$this->type}.default");
108 $this->assertNull($display->getComponent('field_test'));
110 // Restore the field to the content region.
112 'fields[field_test][type]' => 'field_test_default',
113 'fields[field_test][region]' => 'content',
115 $this->drupalPostForm($manage_display, $edit, t('Save'));
117 // Change the formatter and check that the summary is updated.
119 'fields[field_test][type]' => 'field_test_multiple',
120 'fields[field_test][region]' => 'content',
121 'refresh_rows' => 'field_test',
123 $this->drupalPostAjaxForm(NULL, $edit, ['op' => t('Refresh')]);
124 $format = 'field_test_multiple';
125 $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
126 $setting_name = key($default_settings);
127 $setting_value = $default_settings[$setting_name];
128 $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
129 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
131 // Submit the form and check that the display is updated.
132 $this->drupalPostForm(NULL, [], t('Save'));
133 $display = entity_get_display('node', $this->type, 'default');
134 $display_options = $display->getComponent('field_test');
135 $current_format = $display_options['type'];
136 $current_setting_value = $display_options['settings'][$setting_name];
137 $this->assertEqual($current_format, $format, 'The formatter was updated.');
138 $this->assertEqual($current_setting_value, $setting_value, 'The setting was updated.');
140 // Assert that hook_field_formatter_settings_summary_alter() is called.
141 $this->assertText('field_test_field_formatter_settings_summary_alter');
143 // Click on the formatter settings button to open the formatter settings
145 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
147 // Assert that the field added in
148 // field_test_field_formatter_third_party_settings_form() is present.
149 $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
150 $this->assertField($fieldname, 'The field added in hook_field_formatter_third_party_settings_form() is present on the settings form.');
151 $edit = [$fieldname => 'foo'];
152 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
154 // Save the form to save the third party settings.
155 $this->drupalPostForm(NULL, [], t('Save'));
157 \Drupal::entityManager()->clearCachedFieldDefinitions();
158 $id = 'node.' . $this->type . '.default';
159 $storage = $this->container->get('entity_type.manager')->getStorage('entity_view_display');
160 $storage->resetCache([$id]);
161 $display = $storage->load($id);
162 $this->assertEqual($display->getRenderer('field_test')->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'), 'foo');
163 $this->assertTrue(in_array('field_third_party_test', $display->calculateDependencies()->getDependencies()['module']), 'The display has a dependency on field_third_party_test module.');
165 // Confirm that the third party settings are not updated on the settings form.
166 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
167 $this->assertFieldByName($fieldname, '');
169 // Test the empty setting formatter.
171 'fields[field_test][type]' => 'field_empty_setting',
172 'fields[field_test][region]' => 'content',
174 $this->drupalPostForm(NULL, $edit, t('Save'));
175 $this->assertNoText('Default empty setting now has a value.');
176 $this->assertFieldById('edit-fields-field-test-settings-edit');
177 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
178 $fieldname = 'fields[field_test][settings_edit_form][settings][field_empty_setting]';
179 $edit = [$fieldname => 'non empty setting'];
180 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
181 $this->assertText('Default empty setting now has a value.');
183 // Test the settings form behavior. An edit button should be present since
184 // there are third party settings to configure.
186 'fields[field_test][type]' => 'field_no_settings',
187 'fields[field_test][region]' => 'content',
188 'refresh_rows' => 'field_test',
190 $this->drupalPostAjaxForm(NULL, $edit, ['op' => t('Refresh')]);
191 $this->assertFieldByName('field_test_settings_edit');
193 // Make sure we can save the third party settings when there are no settings available
194 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
195 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
197 // When a module providing third-party settings to a formatter (or widget)
198 // is uninstalled, the formatter remains enabled but the provided settings,
199 // together with the corresponding form elements, are removed from the
200 // display component.
201 \Drupal::service('module_installer')->uninstall(['field_third_party_test']);
203 // Ensure the button is still there after the module has been disabled.
204 $this->drupalGet($manage_display);
205 $this->assertResponse(200);
206 $this->assertFieldByName('field_test_settings_edit');
208 // Ensure that third-party form elements are not present anymore.
209 $this->drupalPostAjaxForm(NULL, [], 'field_test_settings_edit');
210 $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
211 $this->assertNoField($fieldname);
213 // Ensure that third-party settings were removed from the formatter.
214 $display = EntityViewDisplay::load("node.{$this->type}.default");
215 $component = $display->getComponent('field_test');
216 $this->assertFalse(array_key_exists('field_third_party_test', $component['third_party_settings']));
220 * Tests widget settings.
222 public function testWidgetUI() {
223 // Admin Manage Fields page.
224 $manage_fields = 'admin/structure/types/manage/' . $this->type;
225 // Admin Manage Display page.
226 $manage_display = $manage_fields . '/form-display';
228 // Creates a new field that can be used with multiple formatters.
229 // Reference: Drupal\field_test\Plugin\Field\FieldWidget\TestFieldWidgetMultiple::isApplicable().
230 $this->fieldUIAddNewField($manage_fields, 'test', 'Test field');
232 // Get the display options (formatter and settings) that were automatically
233 // assigned for the 'default' display.
234 $display = entity_get_form_display('node', $this->type, 'default');
235 $display_options = $display->getComponent('field_test');
236 $widget_type = $display_options['type'];
237 $default_settings = \Drupal::service('plugin.manager.field.widget')->getDefaultSettings($widget_type);
238 $setting_name = key($default_settings);
239 $setting_value = $display_options['settings'][$setting_name];
241 // Display the "Manage form display" screen and check if the expected
242 // widget is selected.
243 $this->drupalGet($manage_display);
244 $this->assertFieldByName('fields[field_test][type]', $widget_type, 'The expected widget is selected.');
245 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
247 // Check whether widget weights are respected.
248 $result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-fields-field-test-type']);
249 $options = array_map(function ($item) {
250 return (string) $item->attributes()->value[0];
252 $expected_options = [
254 'test_field_widget_multilingual',
255 'test_field_widget_multiple',
257 $this->assertEqual($options, $expected_options, 'The expected widget ordering is respected.');
259 // Change the widget and check that the summary is updated.
261 'fields[field_test][type]' => 'test_field_widget_multiple',
262 'fields[field_test][region]' => 'content',
263 'refresh_rows' => 'field_test',
265 $this->drupalPostAjaxForm(NULL, $edit, ['op' => t('Refresh')]);
266 $widget_type = 'test_field_widget_multiple';
267 $default_settings = \Drupal::service('plugin.manager.field.widget')->getDefaultSettings($widget_type);
268 $setting_name = key($default_settings);
269 $setting_value = $default_settings[$setting_name];
270 $this->assertFieldByName('fields[field_test][type]', $widget_type, 'The expected widget is selected.');
271 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
273 // Submit the form and check that the display is updated.
274 $this->drupalPostForm(NULL, [], t('Save'));
275 $display = entity_get_form_display('node', $this->type, 'default');
276 $display_options = $display->getComponent('field_test');
277 $current_widget = $display_options['type'];
278 $current_setting_value = $display_options['settings'][$setting_name];
279 $this->assertEqual($current_widget, $widget_type, 'The widget was updated.');
280 $this->assertEqual($current_setting_value, $setting_value, 'The setting was updated.');
282 // Assert that hook_field_widget_settings_summary_alter() is called.
283 $this->assertText('field_test_field_widget_settings_summary_alter');
285 // Click on the widget settings button to open the widget settings form.
286 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
288 // Assert that the field added in
289 // field_test_field_widget_third_party_settings_form() is present.
290 $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_widget_third_party_settings_form]';
291 $this->assertField($fieldname, 'The field added in hook_field_widget_third_party_settings_form() is present on the settings form.');
292 $edit = [$fieldname => 'foo'];
293 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
295 // Save the form to save the third party settings.
296 $this->drupalPostForm(NULL, [], t('Save'));
297 \Drupal::entityManager()->clearCachedFieldDefinitions();
298 $storage = $this->container->get('entity_type.manager')->getStorage('entity_form_display');
299 $storage->resetCache(['node.' . $this->type . '.default']);
300 $display = $storage->load('node.' . $this->type . '.default');
301 $this->assertEqual($display->getRenderer('field_test')->getThirdPartySetting('field_third_party_test', 'field_test_widget_third_party_settings_form'), 'foo');
302 $this->assertTrue(in_array('field_third_party_test', $display->calculateDependencies()->getDependencies()['module']), 'Form display does not have a dependency on field_third_party_test module.');
304 // Confirm that the third party settings are not updated on the settings form.
305 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
306 $this->assertFieldByName($fieldname, '');
308 // Creates a new field that can not be used with the multiple formatter.
309 // Reference: Drupal\field_test\Plugin\Field\FieldWidget\TestFieldWidgetMultiple::isApplicable().
310 $this->fieldUIAddNewField($manage_fields, 'onewidgetfield', 'One Widget Field');
312 // Go to the Manage Form Display.
313 $this->drupalGet($manage_display);
315 // Checks if the select elements contain the specified options.
316 $this->assertFieldSelectOptions('fields[field_test][type]', ['test_field_widget', 'test_field_widget_multilingual', 'test_field_widget_multiple']);
317 $this->assertFieldSelectOptions('fields[field_onewidgetfield][type]', ['test_field_widget', 'test_field_widget_multilingual']);
319 // Ensure that fields can be hidden directly by changing the region.
320 $this->assertFieldByName('fields[field_test][region]', 'content');
321 $edit = ['fields[field_test][region]' => 'hidden'];
322 $this->drupalPostForm(NULL, $edit, t('Save'));
323 $this->assertFieldByName('fields[field_test][region]', 'hidden');
324 $display = EntityFormDisplay::load("node.{$this->type}.default");
325 $this->assertNull($display->getComponent('field_test'));
329 * Tests switching view modes to use custom or 'default' settings'.
331 public function testViewModeCustom() {
332 // Create a field, and a node with some data for the field.
333 $this->fieldUIAddNewField('admin/structure/types/manage/' . $this->type, 'test', 'Test field');
334 \Drupal::entityManager()->clearCachedFieldDefinitions();
335 // For this test, use a formatter setting value that is an integer unlikely
336 // to appear in a rendered node other than as part of the field being tested
337 // (for example, unlikely to be part of the "Submitted by ... on ..." line).
340 'type' => $this->type,
341 'field_test' => [['value' => $value]],
343 $node = $this->drupalCreateNode($settings);
345 // Gather expected output values with the various formatters.
346 $formatter_plugin_manager = \Drupal::service('plugin.manager.field.formatter');
347 $field_test_default_settings = $formatter_plugin_manager->getDefaultSettings('field_test_default');
348 $field_test_with_prepare_view_settings = $formatter_plugin_manager->getDefaultSettings('field_test_with_prepare_view');
350 'field_test_default' => $field_test_default_settings['test_formatter_setting'] . '|' . $value,
351 'field_test_with_prepare_view' => $field_test_with_prepare_view_settings['test_formatter_setting_additional'] . '|' . $value . '|' . ($value + 1),
354 // Check that the field is displayed with the default formatter in 'rss'
355 // mode (uses 'default'), and hidden in 'teaser' mode (uses custom settings).
356 $this->assertNodeViewText($node, 'rss', $output['field_test_default'], "The field is displayed as expected in view modes that use 'default' settings.");
357 $this->assertNodeViewNoText($node, 'teaser', $value, "The field is hidden in view modes that use custom settings.");
359 // Change formatter for 'default' mode, check that the field is displayed
360 // accordingly in 'rss' mode.
362 'fields[field_test][type]' => 'field_test_with_prepare_view',
363 'fields[field_test][region]' => 'content',
365 $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display', $edit, t('Save'));
366 $this->assertNodeViewText($node, 'rss', $output['field_test_with_prepare_view'], "The field is displayed as expected in view modes that use 'default' settings.");
368 // Specialize the 'rss' mode, check that the field is displayed the same.
370 "display_modes_custom[rss]" => TRUE,
372 $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display', $edit, t('Save'));
373 $this->assertNodeViewText($node, 'rss', $output['field_test_with_prepare_view'], "The field is displayed as expected in newly specialized 'rss' mode.");
375 // Set the field to 'hidden' in the view mode, check that the field is
378 'fields[field_test][region]' => 'hidden',
380 $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display/rss', $edit, t('Save'));
381 $this->assertNodeViewNoText($node, 'rss', $value, "The field is hidden in 'rss' mode.");
383 // Set the view mode back to 'default', check that the field is displayed
386 "display_modes_custom[rss]" => FALSE,
388 $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display', $edit, t('Save'));
389 $this->assertNodeViewText($node, 'rss', $output['field_test_with_prepare_view'], "The field is displayed as expected when 'rss' mode is set back to 'default' settings.");
391 // Specialize the view mode again.
393 "display_modes_custom[rss]" => TRUE,
395 $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display', $edit, t('Save'));
396 // Check that the previous settings for the view mode have been kept.
397 $this->assertNodeViewNoText($node, 'rss', $value, "The previous settings are kept when 'rss' mode is specialized again.");
401 * Tests the local tasks are displayed correctly for view modes.
403 public function testViewModeLocalTasks() {
404 $manage_display = 'admin/structure/types/manage/' . $this->type . '/display';
405 $this->drupalGet($manage_display);
406 $this->assertNoLink('Full content');
407 $this->assertLink('Teaser');
409 $this->drupalGet($manage_display . '/teaser');
410 $this->assertNoLink('Full content');
411 $this->assertLink('Default');
415 * Tests that fields with no explicit display settings do not break.
417 public function testNonInitializedFields() {
418 // Create a test field.
419 $this->fieldUIAddNewField('admin/structure/types/manage/' . $this->type, 'test', 'Test');
421 // Check that the field appears as 'hidden' on the 'Manage display' page
422 // for the 'teaser' mode.
423 $this->drupalGet('admin/structure/types/manage/' . $this->type . '/display/teaser');
424 $this->assertFieldByName('fields[field_test][region]', 'hidden', 'The field is displayed as \'hidden \'.');
428 * Tests hiding the view modes fieldset when there's only one available.
430 public function testSingleViewMode() {
431 $this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary . '/display');
432 $this->assertNoText('Use custom display settings for the following view modes', 'Custom display settings fieldset found.');
434 // This may not trigger a notice when 'view_modes_custom' isn't available.
435 $this->drupalPostForm('admin/structure/taxonomy/manage/' . $this->vocabulary . '/overview/display', [], t('Save'));
439 * Tests that a message is shown when there are no fields.
441 public function testNoFieldsDisplayOverview() {
442 // Create a fresh content type without any fields.
444 'type' => 'no_fields',
445 'name' => 'No fields',
448 $this->drupalGet('admin/structure/types/manage/no_fields/display');
449 $this->assertRaw(t('There are no fields yet added. You can add new fields on the <a href=":link">Manage fields</a> page.', [':link' => \Drupal::url('entity.node.field_ui_fields', ['node_type' => 'no_fields'])]));
453 * Asserts that a string is found in the rendered node in a view mode.
455 * @param \Drupal\Core\Entity\EntityInterface $node
458 * The view mode in which the node should be displayed.
460 * Plain text to look for.
462 * Message to display.
465 * TRUE on pass, FALSE on fail.
467 public function assertNodeViewText(EntityInterface $node, $view_mode, $text, $message) {
468 return $this->assertNodeViewTextHelper($node, $view_mode, $text, $message, FALSE);
472 * Asserts that a string is not found in the rendered node in a view mode.
474 * @param \Drupal\Core\Entity\EntityInterface $node
477 * The view mode in which the node should be displayed.
479 * Plain text to look for.
481 * Message to display.
483 * TRUE on pass, FALSE on fail.
485 public function assertNodeViewNoText(EntityInterface $node, $view_mode, $text, $message) {
486 return $this->assertNodeViewTextHelper($node, $view_mode, $text, $message, TRUE);
490 * Asserts that a string is (not) found in the rendered node in a view mode.
492 * This helper function is used by assertNodeViewText() and
493 * assertNodeViewNoText().
495 * @param \Drupal\Core\Entity\EntityInterface $node
498 * The view mode in which the node should be displayed.
500 * Plain text to look for.
502 * Message to display.
504 * TRUE if this text should not exist, FALSE if it should.
507 * TRUE on pass, FALSE on fail.
509 public function assertNodeViewTextHelper(EntityInterface $node, $view_mode, $text, $message, $not_exists) {
510 // Make sure caches on the tester side are refreshed after changes
511 // submitted on the tested side.
512 \Drupal::entityManager()->clearCachedFieldDefinitions();
514 // Save current content so that we can restore it when we're done.
515 $old_content = $this->getRawContent();
517 // Render a cloned node, so that we do not alter the original.
518 $clone = clone $node;
519 $element = node_view($clone, $view_mode);
520 $output = \Drupal::service('renderer')->renderRoot($element);
521 $this->verbose(t('Rendered node - view mode: @view_mode', ['@view_mode' => $view_mode]) . '<hr />' . $output);
523 // Assign content so that WebTestBase functions can be used.
524 $this->setRawContent($output);
525 $method = ($not_exists ? 'assertNoText' : 'assertText');
526 $return = $this->{$method}((string) $text, $message);
528 // Restore previous content.
529 $this->setRawContent($old_content);
535 * Checks if a select element contains the specified options.
537 * @param string $name
539 * @param array $expected_options
540 * An array of expected options.
543 * TRUE if the assertion succeeded, FALSE otherwise.
545 protected function assertFieldSelectOptions($name, array $expected_options) {
546 $xpath = $this->buildXPathQuery('//select[@name=:name]', [':name' => $name]);
547 $fields = $this->xpath($xpath);
550 $options = $this->getAllOptionsList($field);
553 sort($expected_options);
555 return $this->assertIdentical($options, $expected_options);
558 return $this->fail('Unable to find field ' . $name);
563 * Extracts all options from a select element.
565 * @param \SimpleXMLElement $element
566 * The select element field information.
569 * An array of option values as strings.
571 protected function getAllOptionsList(\SimpleXMLElement $element) {
573 // Add all options items.
574 foreach ($element->option as $option) {
575 $options[] = (string) $option['value'];
578 // Loops trough all the option groups
579 foreach ($element->optgroup as $optgroup) {
580 $options = array_merge($this->getAllOptionsList($optgroup), $options);