3 namespace Drupal\views_ui;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\SafeMarkup;
7 use Drupal\Core\Ajax\AjaxResponse;
8 use Drupal\Core\Ajax\HtmlCommand;
9 use Drupal\Core\Ajax\ReplaceCommand;
10 use Drupal\Core\Datetime\DateFormatterInterface;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Render\ElementInfoManagerInterface;
14 use Drupal\user\SharedTempStoreFactory;
15 use Drupal\views\Views;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17 use Symfony\Component\HttpFoundation\RequestStack;
20 * Form controller for the Views edit form.
22 class ViewEditForm extends ViewFormBase {
25 * The views temp store.
27 * @var \Drupal\user\SharedTempStore
34 * @var \Symfony\Component\HttpFoundation\RequestStack
36 protected $requestStack;
39 * The date formatter service.
41 * @var \Drupal\Core\Datetime\DateFormatterInterface
43 protected $dateFormatter;
46 * The element info manager.
48 * @var \Drupal\Core\Render\ElementInfoManagerInterface
50 protected $elementInfo;
53 * Constructs a new ViewEditForm object.
55 * @param \Drupal\user\SharedTempStoreFactory $temp_store_factory
56 * The factory for the temp store object.
57 * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
58 * The request stack object.
59 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
60 * The date Formatter service.
61 * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
62 * The element info manager.
64 public function __construct(SharedTempStoreFactory $temp_store_factory, RequestStack $requestStack, DateFormatterInterface $date_formatter, ElementInfoManagerInterface $element_info) {
65 $this->tempStore = $temp_store_factory->get('views');
66 $this->requestStack = $requestStack;
67 $this->dateFormatter = $date_formatter;
68 $this->elementInfo = $element_info;
74 public static function create(ContainerInterface $container) {
76 $container->get('user.shared_tempstore'),
77 $container->get('request_stack'),
78 $container->get('date.formatter'),
79 $container->get('element_info')
86 public function form(array $form, FormStateInterface $form_state) {
87 $view = $this->entity;
88 $display_id = $this->displayID;
89 // Do not allow the form to be cached, because $form_state->get('view') can become
90 // stale between page requests.
91 // See views_ui_ajax_get_form() for how this affects #ajax.
92 // @todo To remove this and allow the form to be cacheable:
93 // - Change $form_state->get('view') to $form_state->getTemporary()['view'].
94 // - Add a #process function to initialize $form_state->getTemporary()['view']
95 // on cached form submissions.
96 // - Use \Drupal\Core\Form\FormStateInterface::loadInclude().
97 $form_state->disableCache();
100 if (!$view->getExecutable()->setDisplay($display_id)) {
101 $form['#markup'] = $this->t('Invalid display id @display', ['@display' => $display_id]);
106 $form['#tree'] = TRUE;
108 $form['#attached']['library'][] = 'core/jquery.ui.tabs';
109 $form['#attached']['library'][] = 'core/jquery.ui.dialog';
110 $form['#attached']['library'][] = 'core/drupal.states';
111 $form['#attached']['library'][] = 'core/drupal.tabledrag';
112 $form['#attached']['library'][] = 'views_ui/views_ui.admin';
113 $form['#attached']['library'][] = 'views_ui/admin.styling';
120 $view_status = $view->status() ? 'enabled' : 'disabled';
121 $form['#prefix'] .= '<div class="views-edit-view views-admin ' . $view_status . ' clearfix">';
122 $form['#suffix'] = '</div>' . $form['#suffix'];
124 $form['#attributes']['class'] = ['form-edit'];
126 if ($view->isLocked()) {
128 '#theme' => 'username',
129 '#account' => $this->entityManager->getStorage('user')->load($view->lock->owner),
131 $lock_message_substitutions = [
132 '@user' => drupal_render($username),
133 '@age' => $this->dateFormatter->formatTimeDiffSince($view->lock->updated),
134 ':url' => $view->url('break-lock-form'),
137 '#type' => 'container',
138 '#attributes' => ['class' => ['view-locked', 'messages', 'messages--warning']],
139 '#children' => $this->t('This view is being edited by user @user, and is therefore locked from editing by others. This lock is @age old. Click here to <a href=":url">break this lock</a>.', $lock_message_substitutions),
145 '#type' => 'container',
146 '#attributes' => ['class' => ['view-changed', 'messages', 'messages--warning']],
147 '#children' => $this->t('You have unsaved changes.'),
150 if (empty($view->changed)) {
151 $form['changed']['#attributes']['class'][] = 'js-hide';
155 $form['displays'] = [
156 '#prefix' => '<h1 class="unit-title clearfix">' . $this->t('Displays') . '</h1>',
157 '#type' => 'container',
166 $form['displays']['top'] = $this->renderDisplayTop($view);
168 // The rest requires a display to be selected.
170 $form_state->set('display_id', $display_id);
172 // The part of the page where editing will take place.
173 $form['displays']['settings'] = [
174 '#type' => 'container',
175 '#id' => 'edit-display-settings',
177 'class' => ['edit-display-settings'],
181 // Add a text that the display is disabled.
182 if ($view->getExecutable()->displayHandlers->has($display_id)) {
183 if (!$view->getExecutable()->displayHandlers->get($display_id)->isEnabled()) {
184 $form['displays']['settings']['disabled']['#markup'] = $this->t('This display is disabled.');
188 // Add the edit display content
189 $tab_content = $this->getDisplayTab($view);
190 $tab_content['#theme_wrappers'] = ['container'];
191 $tab_content['#attributes'] = ['class' => ['views-display-tab']];
192 $tab_content['#id'] = 'views-tab-' . $display_id;
193 // Mark deleted displays as such.
194 $display = $view->get('display');
195 if (!empty($display[$display_id]['deleted'])) {
196 $tab_content['#attributes']['class'][] = 'views-display-deleted';
198 // Mark disabled displays as such.
200 if ($view->getExecutable()->displayHandlers->has($display_id) && !$view->getExecutable()->displayHandlers->get($display_id)->isEnabled()) {
201 $tab_content['#attributes']['class'][] = 'views-display-disabled';
203 $form['displays']['settings']['settings_content'] = [
204 '#type' => 'container',
205 'tab_content' => $tab_content,
215 protected function actions(array $form, FormStateInterface $form_state) {
216 $actions = parent::actions($form, $form_state);
217 unset($actions['delete']);
219 $actions['cancel'] = [
221 '#value' => $this->t('Cancel'),
222 '#submit' => ['::cancel'],
223 '#limit_validation_errors' => [],
225 if ($this->entity->isLocked()) {
226 $actions['submit']['#access'] = FALSE;
227 $actions['cancel']['#access'] = FALSE;
235 public function validateForm(array &$form, FormStateInterface $form_state) {
236 parent::validateForm($form, $form_state);
238 $view = $this->entity;
239 if ($view->isLocked()) {
240 $form_state->setErrorByName('', $this->t('Changes cannot be made to a locked view.'));
242 foreach ($view->getExecutable()->validate() as $display_errors) {
243 foreach ($display_errors as $error) {
244 $form_state->setErrorByName('', $error);
252 public function save(array $form, FormStateInterface $form_state) {
253 $view = $this->entity;
254 $executable = $view->getExecutable();
255 $executable->initDisplay();
257 // Go through and remove displayed scheduled for removal.
258 $displays = $view->get('display');
259 foreach ($displays as $id => $display) {
260 if (!empty($display['deleted'])) {
261 // Remove view display from view attachment under the attachments
263 $display_handler = $executable->displayHandlers->get($id);
264 if ($attachments = $display_handler->getAttachedDisplays()) {
265 foreach ($attachments as $attachment ) {
266 $attached_options = $executable->displayHandlers->get($attachment)->getOption('displays');
267 unset($attached_options[$id]);
268 $executable->displayHandlers->get($attachment)->setOption('displays', $attached_options);
271 $executable->displayHandlers->remove($id);
272 unset($displays[$id]);
276 // Rename display ids if needed.
277 foreach ($executable->displayHandlers as $id => $display) {
278 if (!empty($display->display['new_id']) && empty($display->display['deleted'])) {
279 $new_id = $display->display['new_id'];
280 $display->display['id'] = $new_id;
281 unset($display->display['new_id']);
282 $executable->displayHandlers->set($new_id, $display);
284 $displays[$new_id] = $displays[$id];
285 unset($displays[$id]);
287 // Redirect the user to the renamed display to be sure that the page itself exists and doesn't throw errors.
288 $form_state->setRedirect('entity.view.edit_display_form', [
289 'view' => $view->id(),
290 'display_id' => $new_id,
294 $view->set('display', $displays);
296 // @todo: Revisit this when https://www.drupal.org/node/1668866 is in.
297 $query = $this->requestStack->getCurrentRequest()->query;
298 $destination = $query->get('destination');
300 if (!empty($destination)) {
301 // Find out the first display which has a changed path and redirect to this url.
302 $old_view = Views::getView($view->id());
303 $old_view->initDisplay();
304 foreach ($old_view->displayHandlers as $id => $display) {
305 // Only check for displays with a path.
306 $old_path = $display->getOption('path');
307 if (empty($old_path)) {
311 if (($display->getPluginId() == 'page') && ($old_path == $destination) && ($old_path != $view->getExecutable()->displayHandlers->get($id)->getOption('path'))) {
312 $destination = $view->getExecutable()->displayHandlers->get($id)->getOption('path');
313 $query->remove('destination');
316 // @todo Use Url::fromPath() once https://www.drupal.org/node/2351379 is
318 $form_state->setRedirectUrl(Url::fromUri("base:$destination"));
323 drupal_set_message($this->t('The view %name has been saved.', ['%name' => $view->label()]));
325 // Remove this view from cache so we can edit it properly.
326 $this->tempStore->delete($view->id());
330 * Form submission handler for the 'cancel' action.
333 * An associative array containing the structure of the form.
334 * @param \Drupal\Core\Form\FormStateInterface $form_state
335 * The current state of the form.
337 public function cancel(array $form, FormStateInterface $form_state) {
338 // Remove this view from cache so edits will be lost.
339 $view = $this->entity;
340 $this->tempStore->delete($view->id());
341 $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
345 * Returns a renderable array representing the edit page for one display.
347 public function getDisplayTab($view) {
349 $display_id = $this->displayID;
350 $display = $view->getExecutable()->displayHandlers->get($display_id);
351 // If the plugin doesn't exist, display an error message instead of an edit
353 if (empty($display)) {
354 // @TODO: Improved UX for the case where a plugin is missing.
355 $build['#markup'] = $this->t("Error: Display @display refers to a plugin named '@plugin', but that plugin is not available.", ['@display' => $display->display['id'], '@plugin' => $display->display['display_plugin']]);
357 // Build the content of the edit page.
359 $build['details'] = $this->getDisplayDetails($view, $display->display);
361 // In AJAX context, ViewUI::rebuildCurrentTab() returns this outside of form
362 // context, so hook_form_views_ui_edit_form_alter() is insufficient.
363 \Drupal::moduleHandler()->alter('views_ui_display_tab', $build, $view, $display_id);
368 * Helper function to get the display details section of the edit UI.
373 * A renderable page build array.
375 public function getDisplayDetails($view, $display) {
376 $display_title = $this->getDisplayLabel($view, $display['id'], FALSE);
378 '#theme_wrappers' => ['container'],
379 '#attributes' => ['id' => 'edit-display-settings-details'],
382 $is_display_deleted = !empty($display['deleted']);
383 // The master display cannot be duplicated.
384 $is_default = $display['id'] == 'default';
385 // @todo: Figure out why getOption doesn't work here.
386 $is_enabled = $view->getExecutable()->displayHandlers->get($display['id'])->isEnabled();
388 if ($display['id'] != 'default') {
389 $build['top']['#theme_wrappers'] = ['container'];
390 $build['top']['#attributes']['id'] = 'edit-display-settings-top';
391 $build['top']['#attributes']['class'] = ['views-ui-display-tab-actions', 'edit-display-settings-top', 'views-ui-display-tab-bucket', 'clearfix'];
393 // The Delete, Duplicate and Undo Delete buttons.
394 $build['top']['actions'] = [
395 '#theme_wrappers' => ['dropbutton_wrapper'],
398 // Because some of the 'links' are actually submit buttons, we have to
399 // manually wrap each item in <li> and the whole list in <ul>.
400 $build['top']['actions']['prefix']['#markup'] = '<ul class="dropbutton">';
402 if (!$is_display_deleted) {
404 $build['top']['actions']['enable'] = [
406 '#value' => $this->t('Enable @display_title', ['@display_title' => $display_title]),
407 '#limit_validation_errors' => [],
408 '#submit' => ['::submitDisplayEnable', '::submitDelayDestination'],
409 '#prefix' => '<li class="enable">',
410 "#suffix" => '</li>',
413 // Add a link to view the page unless the view is disabled or has no
415 elseif ($view->status() && $view->getExecutable()->displayHandlers->get($display['id'])->hasPath()) {
416 $path = $view->getExecutable()->displayHandlers->get($display['id'])->getPath();
417 if ($path && (strpos($path, '%') === FALSE)) {
418 if (!parse_url($path, PHP_URL_SCHEME)) {
419 // @todo Views should expect and store a leading /. See:
420 // https://www.drupal.org/node/2423913
421 $url = Url::fromUserInput('/' . ltrim($path, '/'));
424 $url = Url::fromUri("base:$path");
426 $build['top']['actions']['path'] = [
428 '#title' => $this->t('View @display_title', ['@display_title' => $display_title]),
429 '#options' => ['alt' => [$this->t("Go to the real page for this display")]],
431 '#prefix' => '<li class="view">',
432 "#suffix" => '</li>',
437 $build['top']['actions']['duplicate'] = [
439 '#value' => $this->t('Duplicate @display_title', ['@display_title' => $display_title]),
440 '#limit_validation_errors' => [],
441 '#submit' => ['::submitDisplayDuplicate', '::submitDelayDestination'],
442 '#prefix' => '<li class="duplicate">',
443 "#suffix" => '</li>',
446 // Always allow a display to be deleted.
447 $build['top']['actions']['delete'] = [
449 '#value' => $this->t('Delete @display_title', ['@display_title' => $display_title]),
450 '#limit_validation_errors' => [],
451 '#submit' => ['::submitDisplayDelete', '::submitDelayDestination'],
452 '#prefix' => '<li class="delete">',
453 "#suffix" => '</li>',
456 foreach (Views::fetchPluginNames('display', NULL, [$view->get('storage')->get('base_table')]) as $type => $label) {
457 if ($type == $display['display_plugin']) {
461 $build['top']['actions']['duplicate_as'][$type] = [
463 '#value' => $this->t('Duplicate as @type', ['@type' => $label]),
464 '#limit_validation_errors' => [],
465 '#submit' => ['::submitDuplicateDisplayAsType', '::submitDelayDestination'],
466 '#prefix' => '<li class="duplicate">',
467 '#suffix' => '</li>',
472 $build['top']['actions']['undo_delete'] = [
474 '#value' => $this->t('Undo delete of @display_title', ['@display_title' => $display_title]),
475 '#limit_validation_errors' => [],
476 '#submit' => ['::submitDisplayUndoDelete', '::submitDelayDestination'],
477 '#prefix' => '<li class="undo-delete">',
478 "#suffix" => '</li>',
482 $build['top']['actions']['disable'] = [
484 '#value' => $this->t('Disable @display_title', ['@display_title' => $display_title]),
485 '#limit_validation_errors' => [],
486 '#submit' => ['::submitDisplayDisable', '::submitDelayDestination'],
487 '#prefix' => '<li class="disable">',
488 "#suffix" => '</li>',
491 $build['top']['actions']['suffix']['#markup'] = '</ul>';
493 // The area above the three columns.
494 $build['top']['display_title'] = [
495 '#theme' => 'views_ui_display_tab_setting',
496 '#description' => $this->t('Display name'),
497 '#link' => $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($display_title, 'display_title'),
501 $build['columns'] = [];
502 $build['columns']['#theme_wrappers'] = ['container'];
503 $build['columns']['#attributes'] = ['id' => 'edit-display-settings-main', 'class' => ['clearfix', 'views-display-columns']];
505 $build['columns']['first']['#theme_wrappers'] = ['container'];
506 $build['columns']['first']['#attributes'] = ['class' => ['views-display-column', 'first']];
508 $build['columns']['second']['#theme_wrappers'] = ['container'];
509 $build['columns']['second']['#attributes'] = ['class' => ['views-display-column', 'second']];
511 $build['columns']['second']['settings'] = [];
512 $build['columns']['second']['header'] = [];
513 $build['columns']['second']['footer'] = [];
514 $build['columns']['second']['empty'] = [];
515 $build['columns']['second']['pager'] = [];
517 // The third column buckets are wrapped in details.
518 $build['columns']['third'] = [
519 '#type' => 'details',
520 '#title' => $this->t('Advanced'),
521 '#theme_wrappers' => ['details'],
524 'views-display-column',
529 // Collapse the details by default.
530 $build['columns']['third']['#open'] = \Drupal::config('views.settings')->get('ui.show.advanced_column');
532 // Each option (e.g. title, access, display as grid/table/list) fits into one
533 // of several "buckets," or boxes (Format, Fields, Sort, and so on).
536 // Fetch options from the display plugin, with a list of buckets they go into.
538 $view->getExecutable()->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
540 // Place each option into its bucket.
541 foreach ($options as $id => $option) {
542 // Each option self-identifies as belonging in a particular bucket.
543 $buckets[$option['category']]['build'][$id] = $this->buildOptionForm($view, $id, $option, $display);
546 // Place each bucket into the proper column.
547 foreach ($buckets as $id => $bucket) {
548 // Let buckets identify themselves as belonging in a column.
549 if (isset($bucket['column']) && isset($build['columns'][$bucket['column']])) {
550 $column = $bucket['column'];
552 // If a bucket doesn't pick one of our predefined columns to belong to, put
553 // it in the last one.
557 if (isset($bucket['build']) && is_array($bucket['build'])) {
558 $build['columns'][$column][$id] = $bucket['build'];
559 $build['columns'][$column][$id]['#theme_wrappers'][] = 'views_ui_display_tab_bucket';
560 $build['columns'][$column][$id]['#title'] = !empty($bucket['title']) ? $bucket['title'] : '';
561 $build['columns'][$column][$id]['#name'] = $id;
565 $build['columns']['first']['fields'] = $this->getFormBucket($view, 'field', $display);
566 $build['columns']['first']['filters'] = $this->getFormBucket($view, 'filter', $display);
567 $build['columns']['first']['sorts'] = $this->getFormBucket($view, 'sort', $display);
568 $build['columns']['second']['header'] = $this->getFormBucket($view, 'header', $display);
569 $build['columns']['second']['footer'] = $this->getFormBucket($view, 'footer', $display);
570 $build['columns']['second']['empty'] = $this->getFormBucket($view, 'empty', $display);
571 $build['columns']['third']['arguments'] = $this->getFormBucket($view, 'argument', $display);
572 $build['columns']['third']['relationships'] = $this->getFormBucket($view, 'relationship', $display);
578 * Submit handler to add a restore a removed display to a view.
580 public function submitDisplayUndoDelete($form, FormStateInterface $form_state) {
581 $view = $this->entity;
582 // Create the new display
583 $id = $form_state->get('display_id');
584 $displays = $view->get('display');
585 $displays[$id]['deleted'] = FALSE;
586 $view->set('display', $displays);
591 // Redirect to the top-level edit page.
592 $form_state->setRedirect('entity.view.edit_display_form', [
593 'view' => $view->id(),
599 * Submit handler to enable a disabled display.
601 public function submitDisplayEnable($form, FormStateInterface $form_state) {
602 $view = $this->entity;
603 $id = $form_state->get('display_id');
604 // setOption doesn't work because this would might affect upper displays
605 $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', TRUE);
610 // Redirect to the top-level edit page.
611 $form_state->setRedirect('entity.view.edit_display_form', [
612 'view' => $view->id(),
618 * Submit handler to disable display.
620 public function submitDisplayDisable($form, FormStateInterface $form_state) {
621 $view = $this->entity;
622 $id = $form_state->get('display_id');
623 $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', FALSE);
628 // Redirect to the top-level edit page.
629 $form_state->setRedirect('entity.view.edit_display_form', [
630 'view' => $view->id(),
636 * Submit handler to delete a display from a view.
638 public function submitDisplayDelete($form, FormStateInterface $form_state) {
639 $view = $this->entity;
640 $display_id = $form_state->get('display_id');
642 // Mark the display for deletion.
643 $displays = $view->get('display');
644 $displays[$display_id]['deleted'] = TRUE;
645 $view->set('display', $displays);
648 // Redirect to the top-level edit page. The first remaining display will
649 // become the active display.
650 $form_state->setRedirectUrl($view->urlInfo('edit-form'));
654 * Regenerate the current tab for AJAX updates.
656 * @param \Drupal\views_ui\ViewUI $view
657 * The view to regenerate its tab.
658 * @param \Drupal\Core\Ajax\AjaxResponse $response
659 * The response object to add new commands to.
660 * @param string $display_id
661 * The display ID of the tab to regenerate.
663 public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
664 $this->displayID = $display_id;
665 if (!$view->getExecutable()->setDisplay('default')) {
669 // Regenerate the main display area.
670 $build = $this->getDisplayTab($view);
671 $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, $build));
673 // Regenerate the top area so changes to display names and order will appear.
674 $build = $this->renderDisplayTop($view);
675 $response->addCommand(new ReplaceCommand('#views-display-top', $build));
679 * Render the top of the display so it can be updated during ajax operations.
681 public function renderDisplayTop(ViewUI $view) {
682 $display_id = $this->displayID;
683 $element['#theme_wrappers'][] = 'views_ui_container';
684 $element['#attributes']['class'] = ['views-display-top', 'clearfix'];
685 $element['#attributes']['id'] = ['views-display-top'];
687 // Extra actions for the display
688 $element['extra_actions'] = [
689 '#type' => 'dropbutton',
691 'id' => 'views-display-extra-actions',
695 'title' => $this->t('Edit view name/description'),
696 'url' => Url::fromRoute('views_ui.form_edit_details', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
697 'attributes' => ['class' => ['views-ajax-link']],
700 'title' => $this->t('Analyze view'),
701 'url' => Url::fromRoute('views_ui.form_analyze', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
702 'attributes' => ['class' => ['views-ajax-link']],
705 'title' => $this->t('Duplicate view'),
706 'url' => $view->urlInfo('duplicate-form'),
709 'title' => $this->t('Reorder displays'),
710 'url' => Url::fromRoute('views_ui.form_reorder_displays', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
711 'attributes' => ['class' => ['views-ajax-link']],
716 if ($view->access('delete')) {
717 $element['extra_actions']['#links']['delete'] = [
718 'title' => $this->t('Delete view'),
719 'url' => $view->urlInfo('delete-form'),
723 // Let other modules add additional links here.
724 \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
726 if (isset($view->type) && $view->type != $this->t('Default')) {
727 if ($view->type == $this->t('Overridden')) {
728 $element['extra_actions']['#links']['revert'] = [
729 'title' => $this->t('Revert view'),
730 'href' => "admin/structure/views/view/{$view->id()}/revert",
731 'query' => ['destination' => $view->url('edit-form')],
735 $element['extra_actions']['#links']['delete'] = [
736 'title' => $this->t('Delete view'),
737 'url' => $view->urlInfo('delete-form'),
742 // Determine the displays available for editing.
743 if ($tabs = $this->getDisplayTabs($view)) {
745 $tabs[$display_id]['#active'] = TRUE;
747 $tabs['#prefix'] = '<h2 class="visually-hidden">' . $this->t('Secondary tabs') . '</h2><ul id = "views-display-menu-tabs" class="tabs secondary">';
748 $tabs['#suffix'] = '</ul>';
749 $element['tabs'] = $tabs;
752 // Buttons for adding a new display.
753 foreach (Views::fetchPluginNames('display', NULL, [$view->get('base_table')]) as $type => $label) {
754 $element['add_display'][$type] = [
756 '#value' => $this->t('Add @display', ['@display' => $label]),
757 '#limit_validation_errors' => [],
758 '#submit' => ['::submitDisplayAdd', '::submitDelayDestination'],
759 '#attributes' => ['class' => ['add-display']],
760 // Allow JavaScript to remove the 'Add ' prefix from the button label when
761 // placing the button in a "Add" dropdown menu.
762 '#process' => array_merge(['views_ui_form_button_was_clicked'], $this->elementInfo->getInfoProperty('submit', '#process', [])),
763 '#values' => [$this->t('Add @display', ['@display' => $label]), $label],
771 * Submit handler for form buttons that do not complete a form workflow.
773 * The Edit View form is a multistep form workflow, but with state managed by
774 * the SharedTempStore rather than $form_state->setRebuild(). Without this
775 * submit handler, buttons that add or remove displays would redirect to the
776 * destination parameter (e.g., when the Edit View form is linked to from a
777 * contextual link). This handler can be added to buttons whose form submission
778 * should not yet redirect to the destination.
780 public function submitDelayDestination($form, FormStateInterface $form_state) {
781 $request = $this->requestStack->getCurrentRequest();
782 $destination = $request->query->get('destination');
784 $redirect = $form_state->getRedirect();
785 // If there is a destination, and redirects are not explicitly disabled, add
786 // the destination as a query string to the redirect and suppress it for the
788 if (isset($destination) && $redirect !== FALSE) {
789 // Create a valid redirect if one does not exist already.
790 if (!($redirect instanceof Url)) {
791 $redirect = Url::createFromRequest($request);
794 // Add the current destination to the redirect unless one exists already.
795 $options = $redirect->getOptions();
796 if (!isset($options['query']['destination'])) {
797 $options['query']['destination'] = $destination;
798 $redirect->setOptions($options);
801 $form_state->setRedirectUrl($redirect);
802 $request->query->remove('destination');
807 * Submit handler to duplicate a display for a view.
809 public function submitDisplayDuplicate($form, FormStateInterface $form_state) {
810 $view = $this->entity;
811 $display_id = $this->displayID;
813 // Create the new display.
814 $displays = $view->get('display');
815 $display = $view->getExecutable()->newDisplay($displays[$display_id]['display_plugin']);
816 $new_display_id = $display->display['id'];
817 $displays[$new_display_id] = $displays[$display_id];
818 $displays[$new_display_id]['id'] = $new_display_id;
819 $view->set('display', $displays);
821 // By setting the current display the changed marker will appear on the new
823 $view->getExecutable()->current_display = $new_display_id;
826 // Redirect to the new display's edit page.
827 $form_state->setRedirect('entity.view.edit_display_form', [
828 'view' => $view->id(),
829 'display_id' => $new_display_id,
834 * Submit handler to add a display to a view.
836 public function submitDisplayAdd($form, FormStateInterface $form_state) {
837 $view = $this->entity;
838 // Create the new display.
839 $parents = $form_state->getTriggeringElement()['#parents'];
840 $display_type = array_pop($parents);
841 $display = $view->getExecutable()->newDisplay($display_type);
842 $display_id = $display->display['id'];
843 // A new display got added so the asterisks symbol should appear on the new
845 $view->getExecutable()->current_display = $display_id;
848 // Redirect to the new display's edit page.
849 $form_state->setRedirect('entity.view.edit_display_form', [
850 'view' => $view->id(),
851 'display_id' => $display_id,
856 * Submit handler to Duplicate a display as another display type.
858 public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) {
859 /** @var \Drupal\views\ViewEntityInterface $view */
860 $view = $this->entity;
861 $display_id = $this->displayID;
863 // Create the new display.
864 $parents = $form_state->getTriggeringElement()['#parents'];
865 $display_type = array_pop($parents);
867 $new_display_id = $view->duplicateDisplayAsType($display_id, $display_type);
869 // By setting the current display the changed marker will appear on the new
871 $view->getExecutable()->current_display = $new_display_id;
874 // Redirect to the new display's edit page.
875 $form_state->setRedirect('entity.view.edit_display_form', [
876 'view' => $view->id(),
877 'display_id' => $new_display_id,
882 * Build a renderable array representing one option on the edit form.
884 * This function might be more logical as a method on an object, if a suitable
885 * object emerges out of refactoring.
887 public function buildOptionForm(ViewUI $view, $id, $option, $display) {
889 $option_build['#theme'] = 'views_ui_display_tab_setting';
891 $option_build['#description'] = $option['title'];
893 $option_build['#link'] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
895 $option_build['#links'] = [];
896 if (!empty($option['links']) && is_array($option['links'])) {
897 foreach ($option['links'] as $link_id => $link_value) {
898 $option_build['#settings_links'][] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['setting'], $link_id, 'views-button-configure', $link_value);
902 if (!empty($view->getExecutable()->displayHandlers->get($display['id'])->options['defaults'][$id])) {
903 $display_id = 'default';
904 $option_build['#defaulted'] = TRUE;
907 $display_id = $display['id'];
908 if (!$view->getExecutable()->displayHandlers->get($display['id'])->isDefaultDisplay()) {
909 if ($view->getExecutable()->displayHandlers->get($display['id'])->defaultableSections($id)) {
910 $option_build['#overridden'] = TRUE;
914 $option_build['#attributes']['class'][] = Html::cleanCssIdentifier($display_id . '-' . $id);
915 return $option_build;
919 * Add information about a section to a display.
921 public function getFormBucket(ViewUI $view, $type, $display) {
922 $executable = $view->getExecutable();
923 $executable->setDisplay($display['id']);
924 $executable->initStyle();
926 $types = $executable->getHandlerTypes();
929 '#theme_wrappers' => ['views_ui_display_tab_bucket'],
932 $build['#overridden'] = FALSE;
933 $build['#defaulted'] = FALSE;
935 $build['#name'] = $type;
936 $build['#title'] = $types[$type]['title'];
938 $rearrange_url = Url::fromRoute('views_ui.form_rearrange', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id'], 'type' => $type]);
939 $class = 'icon compact rearrange';
941 // Different types now have different rearrange forms, so we use this switch
942 // to get the right one.
945 // The rearrange form for filters contains the and/or UI, so override
947 $rearrange_url = Url::fromRoute('views_ui.form_rearrange_filter', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id']]);
948 // TODO: Add another class to have another symbol for filter rearrange.
949 $class = 'icon compact rearrange';
952 // Fetch the style plugin info so we know whether to list fields or not.
953 $style_plugin = $executable->style_plugin;
954 $uses_fields = $style_plugin && $style_plugin->usesFields();
956 $build['fields'][] = [
957 '#markup' => $this->t('The selected style or row format does not use fields.'),
958 '#theme_wrappers' => ['views_ui_container'],
959 '#attributes' => ['class' => ['views-display-setting']],
967 if (!$executable->display_handler->usesAreas()) {
969 '#markup' => $this->t('The selected display type does not use @type plugins', ['@type' => $type]),
970 '#theme_wrappers' => ['views_ui_container'],
971 '#attributes' => ['class' => ['views-display-setting']],
978 // Create an array of actions to pass to links template.
980 $count_handlers = count($executable->display_handler->getHandlers($type));
982 // Create the add text variable for the add action.
983 $add_text = $this->t('Add <span class="visually-hidden">@type</span>', ['@type' => $types[$type]['ltitle']]);
986 'title' => $add_text,
987 'url' => Url::fromRoute('views_ui.form_add_handler', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id'], 'type' => $type]),
988 'attributes' => ['class' => ['icon compact add', 'views-ajax-link'], 'id' => 'views-add-' . $type],
990 if ($count_handlers > 0) {
991 // Create the rearrange text variable for the rearrange action.
992 $rearrange_text = $type == 'filter' ? $this->t('And/Or Rearrange <span class="visually-hidden">filter criteria</span>') : $this->t('Rearrange <span class="visually-hidden">@type</span>', ['@type' => $types[$type]['ltitle']]);
994 $actions['rearrange'] = [
995 'title' => $rearrange_text,
996 'url' => $rearrange_url,
997 'attributes' => ['class' => [$class, 'views-ajax-link'], 'id' => 'views-rearrange-' . $type],
1001 // Render the array of links
1002 $build['#actions'] = [
1003 '#type' => 'dropbutton',
1004 '#links' => $actions,
1006 'class' => ['views-ui-settings-bucket-operations'],
1010 if (!$executable->display_handler->isDefaultDisplay()) {
1011 if (!$executable->display_handler->isDefaulted($types[$type]['plural'])) {
1012 $build['#overridden'] = TRUE;
1015 $build['#defaulted'] = TRUE;
1019 static $relationships = NULL;
1020 if (!isset($relationships)) {
1021 // Get relationship labels.
1022 $relationships = [];
1023 foreach ($executable->display_handler->getHandlers('relationship') as $id => $handler) {
1024 $relationships[$id] = $handler->adminLabel();
1028 // Filters can now be grouped so we do a little bit extra:
1031 if ($type == 'filter') {
1032 $group_info = $executable->display_handler->getOption('filter_groups');
1033 // If there is only one group but it is using the "OR" filter, we still
1034 // treat it as a group for display purposes, since we want to display the
1035 // "OR" label next to items within the group.
1036 if (!empty($group_info['groups']) && (count($group_info['groups']) > 1 || current($group_info['groups']) == 'OR')) {
1038 $groups = [0 => []];
1042 $build['fields'] = [];
1044 foreach ($executable->display_handler->getOption($types[$type]['plural']) as $id => $field) {
1045 // Build the option link for this handler ("Node: ID = article").
1046 $build['fields'][$id] = [];
1047 $build['fields'][$id]['#theme'] = 'views_ui_display_tab_setting';
1049 $handler = $executable->display_handler->getHandler($type, $id);
1050 if ($handler->broken()) {
1051 $build['fields'][$id]['#class'][] = 'broken';
1052 $field_name = $handler->adminLabel();
1053 $build['fields'][$id]['#link'] = $this->l($field_name, new Url('views_ui.form_handler', [
1055 'view' => $view->id(),
1056 'display_id' => $display['id'],
1059 ], ['attributes' => ['class' => ['views-ajax-link']]]));
1063 $field_name = $handler->adminLabel(TRUE);
1064 if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
1065 $field_name = '(' . $relationships[$field['relationship']] . ') ' . $field_name;
1068 $description = $handler->adminSummary();
1069 $link_text = $field_name . (empty($description) ? '' : " ($description)");
1070 $link_attributes = ['class' => ['views-ajax-link']];
1071 if (!empty($field['exclude'])) {
1072 $link_attributes['class'][] = 'views-field-excluded';
1073 // Add a [hidden] marker, if the field is excluded.
1074 $link_text .= ' [' . $this->t('hidden') . ']';
1076 $build['fields'][$id]['#link'] = $this->l($link_text, new Url('views_ui.form_handler', [
1078 'view' => $view->id(),
1079 'display_id' => $display['id'],
1082 ], ['attributes' => $link_attributes]));
1083 $build['fields'][$id]['#class'][] = Html::cleanCssIdentifier($display['id'] . '-' . $type . '-' . $id);
1085 if ($executable->display_handler->useGroupBy() && $handler->usesGroupBy()) {
1086 $build['fields'][$id]['#settings_links'][] = $this->l(SafeMarkup::format('<span class="label">@text</span>', ['@text' => $this->t('Aggregation settings')]), new Url('views_ui.form_handler_group', [
1088 'view' => $view->id(),
1089 'display_id' => $display['id'],
1092 ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Aggregation settings')]]));
1095 if ($handler->hasExtraOptions()) {
1096 $build['fields'][$id]['#settings_links'][] = $this->l(SafeMarkup::format('<span class="label">@text</span>', ['@text' => $this->t('Settings')]), new Url('views_ui.form_handler_extra', [
1098 'view' => $view->id(),
1099 'display_id' => $display['id'],
1102 ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Settings')]]));
1106 $gid = $handler->options['group'];
1108 // Show in default group if the group does not exist.
1109 if (empty($group_info['groups'][$gid])) {
1112 $groups[$gid][] = $id;
1116 // If using grouping, re-order fields so that they show up properly in the list.
1117 if ($type == 'filter' && $grouping) {
1118 $store = $build['fields'];
1119 $build['fields'] = [];
1120 foreach ($groups as $gid => $contents) {
1121 // Display an operator between each group.
1122 if (!empty($build['fields'])) {
1123 $build['fields'][] = [
1124 '#theme' => 'views_ui_display_tab_setting',
1125 '#class' => ['views-group-text'],
1126 '#link' => ($group_info['operator'] == 'OR' ? $this->t('OR') : $this->t('AND')),
1129 // Display an operator between each pair of filters within the group.
1130 $keys = array_keys($contents);
1132 foreach ($contents as $key => $pid) {
1133 if ($key != $last) {
1134 $operator = $group_info['groups'][$gid] == 'OR' ? $this->t('OR') : $this->t('AND');
1135 $store[$pid]['#link'] = SafeMarkup::format('@link <span>@operator</span>', ['@link' => $store[$pid]['#link'], '@operator' => $operator]);
1137 $build['fields'][$pid] = $store[$pid];