3 namespace Drupal\field_ui\Tests;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Entity\Entity\EntityFormDisplay;
7 use Drupal\Core\Entity\Entity\EntityViewDisplay;
8 use Drupal\Core\Entity\EntityInterface;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\node\Entity\NodeType;
11 use Drupal\simpletest\WebTestBase;
12 use Drupal\taxonomy\Entity\Vocabulary;
15 * Tests the Field UI "Manage display" and "Manage form display" screens.
19 class ManageDisplayTest extends WebTestBase {
28 public static $modules = ['node', 'field_ui', 'taxonomy', 'search', 'field_test', 'field_third_party_test', 'block'];
33 protected function setUp() {
35 $this->drupalPlaceBlock('system_breadcrumb_block');
36 $this->drupalPlaceBlock('local_tasks_block');
38 // Create a test user.
39 $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']);
40 $this->drupalLogin($admin_user);
42 // Create content type, with underscores.
43 $type_name = strtolower($this->randomMachineName(8)) . '_test';
44 $type = $this->drupalCreateContentType(['name' => $type_name, 'type' => $type_name]);
45 $this->type = $type->id();
47 // Create a default vocabulary.
48 $vocabulary = Vocabulary::create([
49 'name' => $this->randomMachineName(),
50 'description' => $this->randomMachineName(),
51 'vid' => Unicode::strtolower($this->randomMachineName()),
52 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
54 'nodes' => ['article' => 'article'],
55 'weight' => mt_rand(0, 10),
58 $this->vocabulary = $vocabulary->id();
62 * Tests formatter settings.
64 public function testFormatterUI() {
65 $manage_fields = 'admin/structure/types/manage/' . $this->type;
66 $manage_display = $manage_fields . '/display';
68 // Create a field, and a node with some data for the field.
69 $this->fieldUIAddNewField($manage_fields, 'test', 'Test field');
71 // Get the display options (formatter and settings) that were automatically
72 // assigned for the 'default' display.
73 $display = entity_get_display('node', $this->type, 'default');
74 $display_options = $display->getComponent('field_test');
75 $format = $display_options['type'];
76 $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
77 $setting_name = key($default_settings);
78 $setting_value = $display_options['settings'][$setting_name];
80 // Display the "Manage display" screen and check that the expected formatter
82 $this->drupalGet($manage_display);
83 $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
84 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
86 // Check whether formatter weights are respected.
87 $result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-fields-field-test-type']);
88 $options = array_map(function($item) {
89 return (string) $item->attributes()->value[0];
94 'field_empty_setting',
96 'field_test_multiple',
97 'field_test_with_prepare_view',
98 'field_test_applicable',
100 $this->assertEqual($options, $expected_options, 'The expected formatter ordering is respected.');
102 // Ensure that fields can be hidden directly by changing the region.
103 $this->drupalGet($manage_display);
104 $this->assertFieldByName('fields[field_test][region]', 'content');
105 $edit = ['fields[field_test][region]' => 'hidden'];
106 $this->drupalPostForm($manage_display, $edit, t('Save'));
107 $this->assertFieldByName('fields[field_test][region]', 'hidden');
108 $display = EntityViewDisplay::load("node.{$this->type}.default");
109 $this->assertNull($display->getComponent('field_test'));
111 // Restore the field to the content region.
113 'fields[field_test][type]' => 'field_test_default',
114 'fields[field_test][region]' => 'content',
116 $this->drupalPostForm($manage_display, $edit, t('Save'));
118 // Change the formatter and check that the summary is updated.
120 'fields[field_test][type]' => 'field_test_multiple',
121 'fields[field_test][region]' => 'content',
122 'refresh_rows' => 'field_test'
124 $this->drupalPostAjaxForm(NULL, $edit, ['op' => t('Refresh')]);
125 $format = 'field_test_multiple';
126 $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
127 $setting_name = key($default_settings);
128 $setting_value = $default_settings[$setting_name];
129 $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
130 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
132 // Submit the form and check that the display is updated.
133 $this->drupalPostForm(NULL, [], t('Save'));
134 $display = entity_get_display('node', $this->type, 'default');
135 $display_options = $display->getComponent('field_test');
136 $current_format = $display_options['type'];
137 $current_setting_value = $display_options['settings'][$setting_name];
138 $this->assertEqual($current_format, $format, 'The formatter was updated.');
139 $this->assertEqual($current_setting_value, $setting_value, 'The setting was updated.');
141 // Assert that hook_field_formatter_settings_summary_alter() is called.
142 $this->assertText('field_test_field_formatter_settings_summary_alter');
144 // Click on the formatter settings button to open the formatter settings
146 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
148 // Assert that the field added in
149 // field_test_field_formatter_third_party_settings_form() is present.
150 $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
151 $this->assertField($fieldname, 'The field added in hook_field_formatter_third_party_settings_form() is present on the settings form.');
152 $edit = [$fieldname => 'foo'];
153 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
155 // Save the form to save the third party settings.
156 $this->drupalPostForm(NULL, [], t('Save'));
158 \Drupal::entityManager()->clearCachedFieldDefinitions();
159 $id = 'node.' . $this->type . '.default';
160 $storage = $this->container->get('entity_type.manager')->getStorage('entity_view_display');
161 $storage->resetCache([$id]);
162 $display = $storage->load($id);
163 $this->assertEqual($display->getRenderer('field_test')->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'), 'foo');
164 $this->assertTrue(in_array('field_third_party_test', $display->calculateDependencies()->getDependencies()['module']), 'The display has a dependency on field_third_party_test module.');
166 // Confirm that the third party settings are not updated on the settings form.
167 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
168 $this->assertFieldByName($fieldname, '');
170 // Test the empty setting formatter.
172 'fields[field_test][type]' => 'field_empty_setting',
173 'fields[field_test][region]' => 'content',
175 $this->drupalPostForm(NULL, $edit, t('Save'));
176 $this->assertNoText('Default empty setting now has a value.');
177 $this->assertFieldById('edit-fields-field-test-settings-edit');
178 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
179 $fieldname = 'fields[field_test][settings_edit_form][settings][field_empty_setting]';
180 $edit = [$fieldname => 'non empty setting'];
181 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
182 $this->assertText('Default empty setting now has a value.');
184 // Test the settings form behavior. An edit button should be present since
185 // there are third party settings to configure.
187 'fields[field_test][type]' => 'field_no_settings',
188 'fields[field_test][region]' => 'content',
189 'refresh_rows' => 'field_test',
191 $this->drupalPostAjaxForm(NULL, $edit, ['op' => t('Refresh')]);
192 $this->assertFieldByName('field_test_settings_edit');
194 // Make sure we can save the third party settings when there are no settings available
195 $this->drupalPostAjaxForm(NULL, [], "field_test_settings_edit");
196 $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
198 // When a module providing third-party settings to a formatter (or widget)
199 // is uninstalled, the formatter remains enabled but the provided settings,
200 // together with the corresponding form elements, are removed from the
201 // display component.
202 \Drupal::service('module_installer')->uninstall(['field_third_party_test']);
204 // Ensure the button is still there after the module has been disabled.
205 $this->drupalGet($manage_display);
206 $this->assertResponse(200);
207 $this->assertFieldByName('field_test_settings_edit');
209 // Ensure that third-party form elements are not present anymore.
210 $this->drupalPostAjaxForm(NULL, [], 'field_test_settings_edit');
211 $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
212 $this->assertNoField($fieldname);
214 // Ensure that third-party settings were removed from the formatter.
215 $display = EntityViewDisplay::load("node.{$this->type}.default");
216 $component = $display->getComponent('field_test');
217 $this->assertFalse(array_key_exists('field_third_party_test', $component['third_party_settings']));
221 * Tests widget settings.
223 public function testWidgetUI() {
224 // Admin Manage Fields page.
225 $manage_fields = 'admin/structure/types/manage/' . $this->type;
226 // Admin Manage Display page.
227 $manage_display = $manage_fields . '/form-display';
229 // Creates a new field that can be used with multiple formatters.
230 // Reference: Drupal\field_test\Plugin\Field\FieldWidget\TestFieldWidgetMultiple::isApplicable().
231 $this->fieldUIAddNewField($manage_fields, 'test', 'Test field');
233 // Get the display options (formatter and settings) that were automatically
234 // assigned for the 'default' display.
235 $display = entity_get_form_display('node', $this->type, 'default');
236 $display_options = $display->getComponent('field_test');
237 $widget_type = $display_options['type'];
238 $default_settings = \Drupal::service('plugin.manager.field.widget')->getDefaultSettings($widget_type);
239 $setting_name = key($default_settings);
240 $setting_value = $display_options['settings'][$setting_name];
242 // Display the "Manage form display" screen and check if the expected
243 // widget is selected.
244 $this->drupalGet($manage_display);
245 $this->assertFieldByName('fields[field_test][type]', $widget_type, 'The expected widget is selected.');
246 $this->assertText("$setting_name: $setting_value", 'The expected summary is displayed.');
248 // Check whether widget weights are respected.
249 $result = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-fields-field-test-type']);
250 $options = array_map(function($item) {
251 return (string) $item->attributes()->value[0];
253 $expected_options = [
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_multiple']);
317 $this->assertFieldSelectOptions('fields[field_onewidgetfield][type]', ['test_field_widget']);
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 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 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 nodein a view mode.
492 * This helper function is used by assertNodeViewText() and
493 * assertNodeViewNoText().
495 * @param 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);