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']) && $display->display['new_id'] !== $display->display['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,
293 elseif (isset($display->display['new_id'])) {
294 unset($display->display['new_id']);
297 $view->set('display', $displays);
299 // @todo: Revisit this when https://www.drupal.org/node/1668866 is in.
300 $query = $this->requestStack->getCurrentRequest()->query;
301 $destination = $query->get('destination');
303 if (!empty($destination)) {
304 // Find out the first display which has a changed path and redirect to this url.
305 $old_view = Views::getView($view->id());
306 $old_view->initDisplay();
307 foreach ($old_view->displayHandlers as $id => $display) {
308 // Only check for displays with a path.
309 $old_path = $display->getOption('path');
310 if (empty($old_path)) {
314 if (($display->getPluginId() == 'page') && ($old_path == $destination) && ($old_path != $view->getExecutable()->displayHandlers->get($id)->getOption('path'))) {
315 $destination = $view->getExecutable()->displayHandlers->get($id)->getOption('path');
316 $query->remove('destination');
319 // @todo Use Url::fromPath() once https://www.drupal.org/node/2351379 is
321 $form_state->setRedirectUrl(Url::fromUri("base:$destination"));
326 drupal_set_message($this->t('The view %name has been saved.', ['%name' => $view->label()]));
328 // Remove this view from cache so we can edit it properly.
329 $this->tempStore->delete($view->id());
333 * Form submission handler for the 'cancel' action.
336 * An associative array containing the structure of the form.
337 * @param \Drupal\Core\Form\FormStateInterface $form_state
338 * The current state of the form.
340 public function cancel(array $form, FormStateInterface $form_state) {
341 // Remove this view from cache so edits will be lost.
342 $view = $this->entity;
343 $this->tempStore->delete($view->id());
344 $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
348 * Returns a renderable array representing the edit page for one display.
350 public function getDisplayTab($view) {
352 $display_id = $this->displayID;
353 $display = $view->getExecutable()->displayHandlers->get($display_id);
354 // If the plugin doesn't exist, display an error message instead of an edit
356 if (empty($display)) {
357 // @TODO: Improved UX for the case where a plugin is missing.
358 $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']]);
360 // Build the content of the edit page.
362 $build['details'] = $this->getDisplayDetails($view, $display->display);
364 // In AJAX context, ViewUI::rebuildCurrentTab() returns this outside of form
365 // context, so hook_form_views_ui_edit_form_alter() is insufficient.
366 \Drupal::moduleHandler()->alter('views_ui_display_tab', $build, $view, $display_id);
371 * Helper function to get the display details section of the edit UI.
376 * A renderable page build array.
378 public function getDisplayDetails($view, $display) {
379 $display_title = $this->getDisplayLabel($view, $display['id'], FALSE);
381 '#theme_wrappers' => ['container'],
382 '#attributes' => ['id' => 'edit-display-settings-details'],
385 $is_display_deleted = !empty($display['deleted']);
386 // The master display cannot be duplicated.
387 $is_default = $display['id'] == 'default';
388 // @todo: Figure out why getOption doesn't work here.
389 $is_enabled = $view->getExecutable()->displayHandlers->get($display['id'])->isEnabled();
391 if ($display['id'] != 'default') {
392 $build['top']['#theme_wrappers'] = ['container'];
393 $build['top']['#attributes']['id'] = 'edit-display-settings-top';
394 $build['top']['#attributes']['class'] = ['views-ui-display-tab-actions', 'edit-display-settings-top', 'views-ui-display-tab-bucket', 'clearfix'];
396 // The Delete, Duplicate and Undo Delete buttons.
397 $build['top']['actions'] = [
398 '#theme_wrappers' => ['dropbutton_wrapper'],
401 // Because some of the 'links' are actually submit buttons, we have to
402 // manually wrap each item in <li> and the whole list in <ul>.
403 $build['top']['actions']['prefix']['#markup'] = '<ul class="dropbutton">';
405 if (!$is_display_deleted) {
407 $build['top']['actions']['enable'] = [
409 '#value' => $this->t('Enable @display_title', ['@display_title' => $display_title]),
410 '#limit_validation_errors' => [],
411 '#submit' => ['::submitDisplayEnable', '::submitDelayDestination'],
412 '#prefix' => '<li class="enable">',
413 "#suffix" => '</li>',
416 // Add a link to view the page unless the view is disabled or has no
418 elseif ($view->status() && $view->getExecutable()->displayHandlers->get($display['id'])->hasPath()) {
419 $path = $view->getExecutable()->displayHandlers->get($display['id'])->getPath();
420 if ($path && (strpos($path, '%') === FALSE)) {
421 if (!parse_url($path, PHP_URL_SCHEME)) {
422 // @todo Views should expect and store a leading /. See:
423 // https://www.drupal.org/node/2423913
424 $url = Url::fromUserInput('/' . ltrim($path, '/'));
427 $url = Url::fromUri("base:$path");
429 $build['top']['actions']['path'] = [
431 '#title' => $this->t('View @display_title', ['@display_title' => $display_title]),
432 '#options' => ['alt' => [$this->t("Go to the real page for this display")]],
434 '#prefix' => '<li class="view">',
435 "#suffix" => '</li>',
440 $build['top']['actions']['duplicate'] = [
442 '#value' => $this->t('Duplicate @display_title', ['@display_title' => $display_title]),
443 '#limit_validation_errors' => [],
444 '#submit' => ['::submitDisplayDuplicate', '::submitDelayDestination'],
445 '#prefix' => '<li class="duplicate">',
446 "#suffix" => '</li>',
449 // Always allow a display to be deleted.
450 $build['top']['actions']['delete'] = [
452 '#value' => $this->t('Delete @display_title', ['@display_title' => $display_title]),
453 '#limit_validation_errors' => [],
454 '#submit' => ['::submitDisplayDelete', '::submitDelayDestination'],
455 '#prefix' => '<li class="delete">',
456 "#suffix" => '</li>',
459 foreach (Views::fetchPluginNames('display', NULL, [$view->get('storage')->get('base_table')]) as $type => $label) {
460 if ($type == $display['display_plugin']) {
464 $build['top']['actions']['duplicate_as'][$type] = [
466 '#value' => $this->t('Duplicate as @type', ['@type' => $label]),
467 '#limit_validation_errors' => [],
468 '#submit' => ['::submitDuplicateDisplayAsType', '::submitDelayDestination'],
469 '#prefix' => '<li class="duplicate">',
470 '#suffix' => '</li>',
475 $build['top']['actions']['undo_delete'] = [
477 '#value' => $this->t('Undo delete of @display_title', ['@display_title' => $display_title]),
478 '#limit_validation_errors' => [],
479 '#submit' => ['::submitDisplayUndoDelete', '::submitDelayDestination'],
480 '#prefix' => '<li class="undo-delete">',
481 "#suffix" => '</li>',
485 $build['top']['actions']['disable'] = [
487 '#value' => $this->t('Disable @display_title', ['@display_title' => $display_title]),
488 '#limit_validation_errors' => [],
489 '#submit' => ['::submitDisplayDisable', '::submitDelayDestination'],
490 '#prefix' => '<li class="disable">',
491 "#suffix" => '</li>',
494 $build['top']['actions']['suffix']['#markup'] = '</ul>';
496 // The area above the three columns.
497 $build['top']['display_title'] = [
498 '#theme' => 'views_ui_display_tab_setting',
499 '#description' => $this->t('Display name'),
500 '#link' => $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($display_title, 'display_title'),
504 $build['columns'] = [];
505 $build['columns']['#theme_wrappers'] = ['container'];
506 $build['columns']['#attributes'] = ['id' => 'edit-display-settings-main', 'class' => ['clearfix', 'views-display-columns']];
508 $build['columns']['first']['#theme_wrappers'] = ['container'];
509 $build['columns']['first']['#attributes'] = ['class' => ['views-display-column', 'first']];
511 $build['columns']['second']['#theme_wrappers'] = ['container'];
512 $build['columns']['second']['#attributes'] = ['class' => ['views-display-column', 'second']];
514 $build['columns']['second']['settings'] = [];
515 $build['columns']['second']['header'] = [];
516 $build['columns']['second']['footer'] = [];
517 $build['columns']['second']['empty'] = [];
518 $build['columns']['second']['pager'] = [];
520 // The third column buckets are wrapped in details.
521 $build['columns']['third'] = [
522 '#type' => 'details',
523 '#title' => $this->t('Advanced'),
524 '#theme_wrappers' => ['details'],
527 'views-display-column',
532 // Collapse the details by default.
533 $build['columns']['third']['#open'] = \Drupal::config('views.settings')->get('ui.show.advanced_column');
535 // Each option (e.g. title, access, display as grid/table/list) fits into one
536 // of several "buckets," or boxes (Format, Fields, Sort, and so on).
539 // Fetch options from the display plugin, with a list of buckets they go into.
541 $view->getExecutable()->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
543 // Place each option into its bucket.
544 foreach ($options as $id => $option) {
545 // Each option self-identifies as belonging in a particular bucket.
546 $buckets[$option['category']]['build'][$id] = $this->buildOptionForm($view, $id, $option, $display);
549 // Place each bucket into the proper column.
550 foreach ($buckets as $id => $bucket) {
551 // Let buckets identify themselves as belonging in a column.
552 if (isset($bucket['column']) && isset($build['columns'][$bucket['column']])) {
553 $column = $bucket['column'];
555 // If a bucket doesn't pick one of our predefined columns to belong to, put
556 // it in the last one.
560 if (isset($bucket['build']) && is_array($bucket['build'])) {
561 $build['columns'][$column][$id] = $bucket['build'];
562 $build['columns'][$column][$id]['#theme_wrappers'][] = 'views_ui_display_tab_bucket';
563 $build['columns'][$column][$id]['#title'] = !empty($bucket['title']) ? $bucket['title'] : '';
564 $build['columns'][$column][$id]['#name'] = $id;
568 $build['columns']['first']['fields'] = $this->getFormBucket($view, 'field', $display);
569 $build['columns']['first']['filters'] = $this->getFormBucket($view, 'filter', $display);
570 $build['columns']['first']['sorts'] = $this->getFormBucket($view, 'sort', $display);
571 $build['columns']['second']['header'] = $this->getFormBucket($view, 'header', $display);
572 $build['columns']['second']['footer'] = $this->getFormBucket($view, 'footer', $display);
573 $build['columns']['second']['empty'] = $this->getFormBucket($view, 'empty', $display);
574 $build['columns']['third']['arguments'] = $this->getFormBucket($view, 'argument', $display);
575 $build['columns']['third']['relationships'] = $this->getFormBucket($view, 'relationship', $display);
581 * Submit handler to add a restore a removed display to a view.
583 public function submitDisplayUndoDelete($form, FormStateInterface $form_state) {
584 $view = $this->entity;
585 // Create the new display
586 $id = $form_state->get('display_id');
587 $displays = $view->get('display');
588 $displays[$id]['deleted'] = FALSE;
589 $view->set('display', $displays);
594 // Redirect to the top-level edit page.
595 $form_state->setRedirect('entity.view.edit_display_form', [
596 'view' => $view->id(),
602 * Submit handler to enable a disabled display.
604 public function submitDisplayEnable($form, FormStateInterface $form_state) {
605 $view = $this->entity;
606 $id = $form_state->get('display_id');
607 // setOption doesn't work because this would might affect upper displays
608 $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', TRUE);
613 // Redirect to the top-level edit page.
614 $form_state->setRedirect('entity.view.edit_display_form', [
615 'view' => $view->id(),
621 * Submit handler to disable display.
623 public function submitDisplayDisable($form, FormStateInterface $form_state) {
624 $view = $this->entity;
625 $id = $form_state->get('display_id');
626 $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', FALSE);
631 // Redirect to the top-level edit page.
632 $form_state->setRedirect('entity.view.edit_display_form', [
633 'view' => $view->id(),
639 * Submit handler to delete a display from a view.
641 public function submitDisplayDelete($form, FormStateInterface $form_state) {
642 $view = $this->entity;
643 $display_id = $form_state->get('display_id');
645 // Mark the display for deletion.
646 $displays = $view->get('display');
647 $displays[$display_id]['deleted'] = TRUE;
648 $view->set('display', $displays);
651 // Redirect to the top-level edit page. The first remaining display will
652 // become the active display.
653 $form_state->setRedirectUrl($view->urlInfo('edit-form'));
657 * Regenerate the current tab for AJAX updates.
659 * @param \Drupal\views_ui\ViewUI $view
660 * The view to regenerate its tab.
661 * @param \Drupal\Core\Ajax\AjaxResponse $response
662 * The response object to add new commands to.
663 * @param string $display_id
664 * The display ID of the tab to regenerate.
666 public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
667 $this->displayID = $display_id;
668 if (!$view->getExecutable()->setDisplay('default')) {
672 // Regenerate the main display area.
673 $build = $this->getDisplayTab($view);
674 $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, $build));
676 // Regenerate the top area so changes to display names and order will appear.
677 $build = $this->renderDisplayTop($view);
678 $response->addCommand(new ReplaceCommand('#views-display-top', $build));
682 * Render the top of the display so it can be updated during ajax operations.
684 public function renderDisplayTop(ViewUI $view) {
685 $display_id = $this->displayID;
686 $element['#theme_wrappers'][] = 'views_ui_container';
687 $element['#attributes']['class'] = ['views-display-top', 'clearfix'];
688 $element['#attributes']['id'] = ['views-display-top'];
690 // Extra actions for the display
691 $element['extra_actions'] = [
692 '#type' => 'dropbutton',
694 'id' => 'views-display-extra-actions',
698 'title' => $this->t('Edit view name/description'),
699 'url' => Url::fromRoute('views_ui.form_edit_details', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
700 'attributes' => ['class' => ['views-ajax-link']],
703 'title' => $this->t('Analyze view'),
704 'url' => Url::fromRoute('views_ui.form_analyze', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
705 'attributes' => ['class' => ['views-ajax-link']],
708 'title' => $this->t('Duplicate view'),
709 'url' => $view->urlInfo('duplicate-form'),
712 'title' => $this->t('Reorder displays'),
713 'url' => Url::fromRoute('views_ui.form_reorder_displays', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display_id]),
714 'attributes' => ['class' => ['views-ajax-link']],
719 if ($view->access('delete')) {
720 $element['extra_actions']['#links']['delete'] = [
721 'title' => $this->t('Delete view'),
722 'url' => $view->urlInfo('delete-form'),
726 // Let other modules add additional links here.
727 \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
729 if (isset($view->type) && $view->type != $this->t('Default')) {
730 if ($view->type == $this->t('Overridden')) {
731 $element['extra_actions']['#links']['revert'] = [
732 'title' => $this->t('Revert view'),
733 'href' => "admin/structure/views/view/{$view->id()}/revert",
734 'query' => ['destination' => $view->url('edit-form')],
738 $element['extra_actions']['#links']['delete'] = [
739 'title' => $this->t('Delete view'),
740 'url' => $view->urlInfo('delete-form'),
745 // Determine the displays available for editing.
746 if ($tabs = $this->getDisplayTabs($view)) {
748 $tabs[$display_id]['#active'] = TRUE;
750 $tabs['#prefix'] = '<h2 class="visually-hidden">' . $this->t('Secondary tabs') . '</h2><ul id = "views-display-menu-tabs" class="tabs secondary">';
751 $tabs['#suffix'] = '</ul>';
752 $element['tabs'] = $tabs;
755 // Buttons for adding a new display.
756 foreach (Views::fetchPluginNames('display', NULL, [$view->get('base_table')]) as $type => $label) {
757 $element['add_display'][$type] = [
759 '#value' => $this->t('Add @display', ['@display' => $label]),
760 '#limit_validation_errors' => [],
761 '#submit' => ['::submitDisplayAdd', '::submitDelayDestination'],
762 '#attributes' => ['class' => ['add-display']],
763 // Allow JavaScript to remove the 'Add ' prefix from the button label when
764 // placing the button in a "Add" dropdown menu.
765 '#process' => array_merge(['views_ui_form_button_was_clicked'], $this->elementInfo->getInfoProperty('submit', '#process', [])),
766 '#values' => [$this->t('Add @display', ['@display' => $label]), $label],
774 * Submit handler for form buttons that do not complete a form workflow.
776 * The Edit View form is a multistep form workflow, but with state managed by
777 * the SharedTempStore rather than $form_state->setRebuild(). Without this
778 * submit handler, buttons that add or remove displays would redirect to the
779 * destination parameter (e.g., when the Edit View form is linked to from a
780 * contextual link). This handler can be added to buttons whose form submission
781 * should not yet redirect to the destination.
783 public function submitDelayDestination($form, FormStateInterface $form_state) {
784 $request = $this->requestStack->getCurrentRequest();
785 $destination = $request->query->get('destination');
787 $redirect = $form_state->getRedirect();
788 // If there is a destination, and redirects are not explicitly disabled, add
789 // the destination as a query string to the redirect and suppress it for the
791 if (isset($destination) && $redirect !== FALSE) {
792 // Create a valid redirect if one does not exist already.
793 if (!($redirect instanceof Url)) {
794 $redirect = Url::createFromRequest($request);
797 // Add the current destination to the redirect unless one exists already.
798 $options = $redirect->getOptions();
799 if (!isset($options['query']['destination'])) {
800 $options['query']['destination'] = $destination;
801 $redirect->setOptions($options);
804 $form_state->setRedirectUrl($redirect);
805 $request->query->remove('destination');
810 * Submit handler to duplicate a display for a view.
812 public function submitDisplayDuplicate($form, FormStateInterface $form_state) {
813 $view = $this->entity;
814 $display_id = $this->displayID;
816 // Create the new display.
817 $displays = $view->get('display');
818 $display = $view->getExecutable()->newDisplay($displays[$display_id]['display_plugin']);
819 $new_display_id = $display->display['id'];
820 $displays[$new_display_id] = $displays[$display_id];
821 $displays[$new_display_id]['id'] = $new_display_id;
822 $view->set('display', $displays);
824 // By setting the current display the changed marker will appear on the new
826 $view->getExecutable()->current_display = $new_display_id;
829 // Redirect to the new display's edit page.
830 $form_state->setRedirect('entity.view.edit_display_form', [
831 'view' => $view->id(),
832 'display_id' => $new_display_id,
837 * Submit handler to add a display to a view.
839 public function submitDisplayAdd($form, FormStateInterface $form_state) {
840 $view = $this->entity;
841 // Create the new display.
842 $parents = $form_state->getTriggeringElement()['#parents'];
843 $display_type = array_pop($parents);
844 $display = $view->getExecutable()->newDisplay($display_type);
845 $display_id = $display->display['id'];
846 // A new display got added so the asterisks symbol should appear on the new
848 $view->getExecutable()->current_display = $display_id;
851 // Redirect to the new display's edit page.
852 $form_state->setRedirect('entity.view.edit_display_form', [
853 'view' => $view->id(),
854 'display_id' => $display_id,
859 * Submit handler to Duplicate a display as another display type.
861 public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) {
862 /** @var \Drupal\views\ViewEntityInterface $view */
863 $view = $this->entity;
864 $display_id = $this->displayID;
866 // Create the new display.
867 $parents = $form_state->getTriggeringElement()['#parents'];
868 $display_type = array_pop($parents);
870 $new_display_id = $view->duplicateDisplayAsType($display_id, $display_type);
872 // By setting the current display the changed marker will appear on the new
874 $view->getExecutable()->current_display = $new_display_id;
877 // Redirect to the new display's edit page.
878 $form_state->setRedirect('entity.view.edit_display_form', [
879 'view' => $view->id(),
880 'display_id' => $new_display_id,
885 * Build a renderable array representing one option on the edit form.
887 * This function might be more logical as a method on an object, if a suitable
888 * object emerges out of refactoring.
890 public function buildOptionForm(ViewUI $view, $id, $option, $display) {
892 $option_build['#theme'] = 'views_ui_display_tab_setting';
894 $option_build['#description'] = $option['title'];
896 $option_build['#link'] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
898 $option_build['#links'] = [];
899 if (!empty($option['links']) && is_array($option['links'])) {
900 foreach ($option['links'] as $link_id => $link_value) {
901 $option_build['#settings_links'][] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['setting'], $link_id, 'views-button-configure', $link_value);
905 if (!empty($view->getExecutable()->displayHandlers->get($display['id'])->options['defaults'][$id])) {
906 $display_id = 'default';
907 $option_build['#defaulted'] = TRUE;
910 $display_id = $display['id'];
911 if (!$view->getExecutable()->displayHandlers->get($display['id'])->isDefaultDisplay()) {
912 if ($view->getExecutable()->displayHandlers->get($display['id'])->defaultableSections($id)) {
913 $option_build['#overridden'] = TRUE;
917 $option_build['#attributes']['class'][] = Html::cleanCssIdentifier($display_id . '-' . $id);
918 return $option_build;
922 * Add information about a section to a display.
924 public function getFormBucket(ViewUI $view, $type, $display) {
925 $executable = $view->getExecutable();
926 $executable->setDisplay($display['id']);
927 $executable->initStyle();
929 $types = $executable->getHandlerTypes();
932 '#theme_wrappers' => ['views_ui_display_tab_bucket'],
935 $build['#overridden'] = FALSE;
936 $build['#defaulted'] = FALSE;
938 $build['#name'] = $type;
939 $build['#title'] = $types[$type]['title'];
941 $rearrange_url = Url::fromRoute('views_ui.form_rearrange', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id'], 'type' => $type]);
942 $class = 'icon compact rearrange';
944 // Different types now have different rearrange forms, so we use this switch
945 // to get the right one.
948 // The rearrange form for filters contains the and/or UI, so override
950 $rearrange_url = Url::fromRoute('views_ui.form_rearrange_filter', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id']]);
951 // TODO: Add another class to have another symbol for filter rearrange.
952 $class = 'icon compact rearrange';
955 // Fetch the style plugin info so we know whether to list fields or not.
956 $style_plugin = $executable->style_plugin;
957 $uses_fields = $style_plugin && $style_plugin->usesFields();
959 $build['fields'][] = [
960 '#markup' => $this->t('The selected style or row format does not use fields.'),
961 '#theme_wrappers' => ['views_ui_container'],
962 '#attributes' => ['class' => ['views-display-setting']],
970 if (!$executable->display_handler->usesAreas()) {
972 '#markup' => $this->t('The selected display type does not use @type plugins', ['@type' => $type]),
973 '#theme_wrappers' => ['views_ui_container'],
974 '#attributes' => ['class' => ['views-display-setting']],
981 // Create an array of actions to pass to links template.
983 $count_handlers = count($executable->display_handler->getHandlers($type));
985 // Create the add text variable for the add action.
986 $add_text = $this->t('Add <span class="visually-hidden">@type</span>', ['@type' => $types[$type]['ltitle']]);
989 'title' => $add_text,
990 'url' => Url::fromRoute('views_ui.form_add_handler', ['js' => 'nojs', 'view' => $view->id(), 'display_id' => $display['id'], 'type' => $type]),
991 'attributes' => ['class' => ['icon compact add', 'views-ajax-link'], 'id' => 'views-add-' . $type],
993 if ($count_handlers > 0) {
994 // Create the rearrange text variable for the rearrange action.
995 $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']]);
997 $actions['rearrange'] = [
998 'title' => $rearrange_text,
999 'url' => $rearrange_url,
1000 'attributes' => ['class' => [$class, 'views-ajax-link'], 'id' => 'views-rearrange-' . $type],
1004 // Render the array of links
1005 $build['#actions'] = [
1006 '#type' => 'dropbutton',
1007 '#links' => $actions,
1009 'class' => ['views-ui-settings-bucket-operations'],
1013 if (!$executable->display_handler->isDefaultDisplay()) {
1014 if (!$executable->display_handler->isDefaulted($types[$type]['plural'])) {
1015 $build['#overridden'] = TRUE;
1018 $build['#defaulted'] = TRUE;
1022 static $relationships = NULL;
1023 if (!isset($relationships)) {
1024 // Get relationship labels.
1025 $relationships = [];
1026 foreach ($executable->display_handler->getHandlers('relationship') as $id => $handler) {
1027 $relationships[$id] = $handler->adminLabel();
1031 // Filters can now be grouped so we do a little bit extra:
1034 if ($type == 'filter') {
1035 $group_info = $executable->display_handler->getOption('filter_groups');
1036 // If there is only one group but it is using the "OR" filter, we still
1037 // treat it as a group for display purposes, since we want to display the
1038 // "OR" label next to items within the group.
1039 if (!empty($group_info['groups']) && (count($group_info['groups']) > 1 || current($group_info['groups']) == 'OR')) {
1041 $groups = [0 => []];
1045 $build['fields'] = [];
1047 foreach ($executable->display_handler->getOption($types[$type]['plural']) as $id => $field) {
1048 // Build the option link for this handler ("Node: ID = article").
1049 $build['fields'][$id] = [];
1050 $build['fields'][$id]['#theme'] = 'views_ui_display_tab_setting';
1052 $handler = $executable->display_handler->getHandler($type, $id);
1053 if ($handler->broken()) {
1054 $build['fields'][$id]['#class'][] = 'broken';
1055 $field_name = $handler->adminLabel();
1056 $build['fields'][$id]['#link'] = $this->l($field_name, new Url('views_ui.form_handler', [
1058 'view' => $view->id(),
1059 'display_id' => $display['id'],
1062 ], ['attributes' => ['class' => ['views-ajax-link']]]));
1066 $field_name = $handler->adminLabel(TRUE);
1067 if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
1068 $field_name = '(' . $relationships[$field['relationship']] . ') ' . $field_name;
1071 $description = $handler->adminSummary();
1072 $link_text = $field_name . (empty($description) ? '' : " ($description)");
1073 $link_attributes = ['class' => ['views-ajax-link']];
1074 if (!empty($field['exclude'])) {
1075 $link_attributes['class'][] = 'views-field-excluded';
1076 // Add a [hidden] marker, if the field is excluded.
1077 $link_text .= ' [' . $this->t('hidden') . ']';
1079 $build['fields'][$id]['#link'] = $this->l($link_text, new Url('views_ui.form_handler', [
1081 'view' => $view->id(),
1082 'display_id' => $display['id'],
1085 ], ['attributes' => $link_attributes]));
1086 $build['fields'][$id]['#class'][] = Html::cleanCssIdentifier($display['id'] . '-' . $type . '-' . $id);
1088 if ($executable->display_handler->useGroupBy() && $handler->usesGroupBy()) {
1089 $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', [
1091 'view' => $view->id(),
1092 'display_id' => $display['id'],
1095 ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Aggregation settings')]]));
1098 if ($handler->hasExtraOptions()) {
1099 $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', [
1101 'view' => $view->id(),
1102 'display_id' => $display['id'],
1105 ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Settings')]]));
1109 $gid = $handler->options['group'];
1111 // Show in default group if the group does not exist.
1112 if (empty($group_info['groups'][$gid])) {
1115 $groups[$gid][] = $id;
1119 // If using grouping, re-order fields so that they show up properly in the list.
1120 if ($type == 'filter' && $grouping) {
1121 $store = $build['fields'];
1122 $build['fields'] = [];
1123 foreach ($groups as $gid => $contents) {
1124 // Display an operator between each group.
1125 if (!empty($build['fields'])) {
1126 $build['fields'][] = [
1127 '#theme' => 'views_ui_display_tab_setting',
1128 '#class' => ['views-group-text'],
1129 '#link' => ($group_info['operator'] == 'OR' ? $this->t('OR') : $this->t('AND')),
1132 // Display an operator between each pair of filters within the group.
1133 $keys = array_keys($contents);
1135 foreach ($contents as $key => $pid) {
1136 if ($key != $last) {
1137 $operator = $group_info['groups'][$gid] == 'OR' ? $this->t('OR') : $this->t('AND');
1138 $store[$pid]['#link'] = SafeMarkup::format('@link <span>@operator</span>', ['@link' => $store[$pid]['#link'], '@operator' => $operator]);
1140 $build['fields'][$pid] = $store[$pid];