67d1229555d2f0733669be862b3659a98301afc3
[yaffs-website] / web / core / modules / views_ui / src / ViewEditForm.php
1 <?php
2
3 namespace Drupal\views_ui;
4
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;
13 use Drupal\Core\Url;
14 use Drupal\user\SharedTempStoreFactory;
15 use Drupal\views\Views;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17 use Symfony\Component\HttpFoundation\RequestStack;
18
19 /**
20  * Form controller for the Views edit form.
21  */
22 class ViewEditForm extends ViewFormBase {
23
24   /**
25    * The views temp store.
26    *
27    * @var \Drupal\user\SharedTempStore
28    */
29   protected $tempStore;
30
31   /**
32    * The request object.
33    *
34    * @var \Symfony\Component\HttpFoundation\RequestStack
35    */
36   protected $requestStack;
37
38   /**
39    * The date formatter service.
40    *
41    * @var \Drupal\Core\Datetime\DateFormatterInterface
42    */
43   protected $dateFormatter;
44
45   /**
46    * The element info manager.
47    *
48    * @var \Drupal\Core\Render\ElementInfoManagerInterface
49    */
50   protected $elementInfo;
51
52   /**
53    * Constructs a new ViewEditForm object.
54    *
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.
63    */
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;
69   }
70
71   /**
72    * {@inheritdoc}
73    */
74   public static function create(ContainerInterface $container) {
75     return new static(
76       $container->get('user.shared_tempstore'),
77       $container->get('request_stack'),
78       $container->get('date.formatter'),
79       $container->get('element_info')
80     );
81   }
82
83   /**
84    * {@inheritdoc}
85    */
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();
98
99     if ($display_id) {
100       if (!$view->getExecutable()->setDisplay($display_id)) {
101         $form['#markup'] = $this->t('Invalid display id @display', ['@display' => $display_id]);
102         return $form;
103       }
104     }
105
106     $form['#tree'] = TRUE;
107
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';
114
115     $form += [
116       '#prefix' => '',
117       '#suffix' => '',
118     ];
119
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'];
123
124     $form['#attributes']['class'] = ['form-edit'];
125
126     if ($view->isLocked()) {
127       $username = [
128         '#theme' => 'username',
129         '#account' => $this->entityManager->getStorage('user')->load($view->lock->owner),
130       ];
131       $lock_message_substitutions = [
132         '@user' => drupal_render($username),
133         '@age' => $this->dateFormatter->formatTimeDiffSince($view->lock->updated),
134         ':url' => $view->url('break-lock-form'),
135       ];
136       $form['locked'] = [
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),
140         '#weight' => -10,
141       ];
142     }
143     else {
144       $form['changed'] = [
145         '#type' => 'container',
146         '#attributes' => ['class' => ['view-changed', 'messages', 'messages--warning']],
147         '#children' => $this->t('You have unsaved changes.'),
148         '#weight' => -10,
149       ];
150       if (empty($view->changed)) {
151         $form['changed']['#attributes']['class'][] = 'js-hide';
152       }
153     }
154
155     $form['displays'] = [
156       '#prefix' => '<h1 class="unit-title clearfix">' . $this->t('Displays') . '</h1>',
157       '#type' => 'container',
158       '#attributes' => [
159         'class' => [
160           'views-displays',
161         ],
162       ],
163     ];
164
165
166     $form['displays']['top'] = $this->renderDisplayTop($view);
167
168     // The rest requires a display to be selected.
169     if ($display_id) {
170       $form_state->set('display_id', $display_id);
171
172       // The part of the page where editing will take place.
173       $form['displays']['settings'] = [
174         '#type' => 'container',
175         '#id' => 'edit-display-settings',
176         '#attributes' => [
177           'class' => ['edit-display-settings'],
178         ],
179       ];
180
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.');
185         }
186       }
187
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';
197       }
198       // Mark disabled displays as such.
199
200       if ($view->getExecutable()->displayHandlers->has($display_id) && !$view->getExecutable()->displayHandlers->get($display_id)->isEnabled()) {
201         $tab_content['#attributes']['class'][] = 'views-display-disabled';
202       }
203       $form['displays']['settings']['settings_content'] = [
204         '#type' => 'container',
205         'tab_content' => $tab_content,
206       ];
207     }
208
209     return $form;
210   }
211
212   /**
213    * {@inheritdoc}
214    */
215   protected function actions(array $form, FormStateInterface $form_state) {
216     $actions = parent::actions($form, $form_state);
217     unset($actions['delete']);
218
219     $actions['cancel'] = [
220       '#type' => 'submit',
221       '#value' => $this->t('Cancel'),
222       '#submit' => ['::cancel'],
223       '#limit_validation_errors' => [],
224     ];
225     if ($this->entity->isLocked()) {
226       $actions['submit']['#access'] = FALSE;
227       $actions['cancel']['#access'] = FALSE;
228     }
229     return $actions;
230   }
231
232   /**
233    * {@inheritdoc}
234    */
235   public function validateForm(array &$form, FormStateInterface $form_state) {
236     parent::validateForm($form, $form_state);
237
238     $view = $this->entity;
239     if ($view->isLocked()) {
240       $form_state->setErrorByName('', $this->t('Changes cannot be made to a locked view.'));
241     }
242     foreach ($view->getExecutable()->validate() as $display_errors) {
243       foreach ($display_errors as $error) {
244         $form_state->setErrorByName('', $error);
245       }
246     }
247   }
248
249   /**
250    * {@inheritdoc}
251    */
252   public function save(array $form, FormStateInterface $form_state) {
253     $view = $this->entity;
254     $executable = $view->getExecutable();
255     $executable->initDisplay();
256
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
262         // options.
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);
269           }
270         }
271         $executable->displayHandlers->remove($id);
272         unset($displays[$id]);
273       }
274     }
275
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);
283
284         $displays[$new_id] = $displays[$id];
285         unset($displays[$id]);
286
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,
291         ]);
292       }
293     }
294     $view->set('display', $displays);
295
296     // @todo: Revisit this when https://www.drupal.org/node/1668866 is in.
297     $query = $this->requestStack->getCurrentRequest()->query;
298     $destination = $query->get('destination');
299
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)) {
308           continue;
309         }
310
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');
314         }
315       }
316       // @todo Use Url::fromPath() once https://www.drupal.org/node/2351379 is
317       //   resolved.
318       $form_state->setRedirectUrl(Url::fromUri("base:$destination"));
319     }
320
321     $view->save();
322
323     drupal_set_message($this->t('The view %name has been saved.', ['%name' => $view->label()]));
324
325     // Remove this view from cache so we can edit it properly.
326     $this->tempStore->delete($view->id());
327   }
328
329   /**
330    * Form submission handler for the 'cancel' action.
331    *
332    * @param array $form
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.
336    */
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'));
342   }
343
344   /**
345    * Returns a renderable array representing the edit page for one display.
346    */
347   public function getDisplayTab($view) {
348     $build = [];
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
352     // page.
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']]);
356     }
357     // Build the content of the edit page.
358     else {
359       $build['details'] = $this->getDisplayDetails($view, $display->display);
360     }
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);
364     return $build;
365   }
366
367   /**
368    * Helper function to get the display details section of the edit UI.
369    *
370    * @param $display
371    *
372    * @return array
373    *   A renderable page build array.
374    */
375   public function getDisplayDetails($view, $display) {
376     $display_title = $this->getDisplayLabel($view, $display['id'], FALSE);
377     $build = [
378       '#theme_wrappers' => ['container'],
379       '#attributes' => ['id' => 'edit-display-settings-details'],
380     ];
381
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();
387
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'];
392
393       // The Delete, Duplicate and Undo Delete buttons.
394       $build['top']['actions'] = [
395         '#theme_wrappers' => ['dropbutton_wrapper'],
396       ];
397
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">';
401
402       if (!$is_display_deleted) {
403         if (!$is_enabled) {
404           $build['top']['actions']['enable'] = [
405             '#type' => 'submit',
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>',
411           ];
412         }
413         // Add a link to view the page unless the view is disabled or has no
414         // path.
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, '/'));
422             }
423             else {
424               $url = Url::fromUri("base:$path");
425             }
426             $build['top']['actions']['path'] = [
427               '#type' => 'link',
428               '#title' => $this->t('View @display_title', ['@display_title' => $display_title]),
429               '#options' => ['alt' => [$this->t("Go to the real page for this display")]],
430               '#url' => $url,
431               '#prefix' => '<li class="view">',
432               "#suffix" => '</li>',
433             ];
434           }
435         }
436         if (!$is_default) {
437           $build['top']['actions']['duplicate'] = [
438             '#type' => 'submit',
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>',
444           ];
445         }
446         // Always allow a display to be deleted.
447         $build['top']['actions']['delete'] = [
448           '#type' => 'submit',
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>',
454         ];
455
456         foreach (Views::fetchPluginNames('display', NULL, [$view->get('storage')->get('base_table')]) as $type => $label) {
457           if ($type == $display['display_plugin']) {
458             continue;
459           }
460
461           $build['top']['actions']['duplicate_as'][$type] = [
462             '#type' => 'submit',
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>',
468           ];
469         }
470       }
471       else {
472         $build['top']['actions']['undo_delete'] = [
473           '#type' => 'submit',
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>',
479         ];
480       }
481       if ($is_enabled) {
482         $build['top']['actions']['disable'] = [
483           '#type' => 'submit',
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>',
489         ];
490       }
491       $build['top']['actions']['suffix']['#markup'] = '</ul>';
492
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'),
498       ];
499     }
500
501     $build['columns'] = [];
502     $build['columns']['#theme_wrappers'] = ['container'];
503     $build['columns']['#attributes'] = ['id' => 'edit-display-settings-main', 'class' => ['clearfix', 'views-display-columns']];
504
505     $build['columns']['first']['#theme_wrappers'] = ['container'];
506     $build['columns']['first']['#attributes'] = ['class' => ['views-display-column', 'first']];
507
508     $build['columns']['second']['#theme_wrappers'] = ['container'];
509     $build['columns']['second']['#attributes'] = ['class' => ['views-display-column', 'second']];
510
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'] = [];
516
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'],
522       '#attributes' => [
523         'class' => [
524           'views-display-column',
525           'third',
526         ],
527       ],
528     ];
529     // Collapse the details by default.
530     $build['columns']['third']['#open'] = \Drupal::config('views.settings')->get('ui.show.advanced_column');
531
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).
534     $buckets = [];
535
536     // Fetch options from the display plugin, with a list of buckets they go into.
537     $options = [];
538     $view->getExecutable()->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
539
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);
544     }
545
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'];
551       }
552       // If a bucket doesn't pick one of our predefined columns to belong to, put
553       // it in the last one.
554       else {
555         $column = 'third';
556       }
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;
562       }
563     }
564
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);
573
574     return $build;
575   }
576
577   /**
578    * Submit handler to add a restore a removed display to a view.
579    */
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);
587
588     // Store in cache
589     $view->cacheSet();
590
591     // Redirect to the top-level edit page.
592     $form_state->setRedirect('entity.view.edit_display_form', [
593       'view' => $view->id(),
594       'display_id' => $id,
595     ]);
596   }
597
598   /**
599    * Submit handler to enable a disabled display.
600    */
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);
606
607     // Store in cache
608     $view->cacheSet();
609
610     // Redirect to the top-level edit page.
611     $form_state->setRedirect('entity.view.edit_display_form', [
612       'view' => $view->id(),
613       'display_id' => $id,
614     ]);
615   }
616
617   /**
618    * Submit handler to disable display.
619    */
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);
624
625     // Store in cache
626     $view->cacheSet();
627
628     // Redirect to the top-level edit page.
629     $form_state->setRedirect('entity.view.edit_display_form', [
630       'view' => $view->id(),
631       'display_id' => $id,
632     ]);
633   }
634
635   /**
636    * Submit handler to delete a display from a view.
637    */
638   public function submitDisplayDelete($form, FormStateInterface $form_state) {
639     $view = $this->entity;
640     $display_id = $form_state->get('display_id');
641
642     // Mark the display for deletion.
643     $displays = $view->get('display');
644     $displays[$display_id]['deleted'] = TRUE;
645     $view->set('display', $displays);
646     $view->cacheSet();
647
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'));
651   }
652
653   /**
654    * Regenerate the current tab for AJAX updates.
655    *
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.
662    */
663   public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
664     $this->displayID = $display_id;
665     if (!$view->getExecutable()->setDisplay('default')) {
666       return;
667     }
668
669     // Regenerate the main display area.
670     $build = $this->getDisplayTab($view);
671     $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, $build));
672
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));
676   }
677
678   /**
679    * Render the top of the display so it can be updated during ajax operations.
680    */
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'];
686
687     // Extra actions for the display
688     $element['extra_actions'] = [
689       '#type' => 'dropbutton',
690       '#attributes' => [
691         'id' => 'views-display-extra-actions',
692       ],
693       '#links' => [
694         'edit-details' => [
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']],
698         ],
699         'analyze' => [
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']],
703         ],
704         'duplicate' => [
705           'title' => $this->t('Duplicate view'),
706           'url' => $view->urlInfo('duplicate-form'),
707         ],
708         'reorder' => [
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']],
712         ],
713       ],
714     ];
715
716     if ($view->access('delete')) {
717       $element['extra_actions']['#links']['delete'] = [
718         'title' => $this->t('Delete view'),
719         'url' => $view->urlInfo('delete-form'),
720       ];
721     }
722
723     // Let other modules add additional links here.
724     \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
725
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')],
732         ];
733       }
734       else {
735         $element['extra_actions']['#links']['delete'] = [
736           'title' => $this->t('Delete view'),
737           'url' => $view->urlInfo('delete-form'),
738         ];
739       }
740     }
741
742     // Determine the displays available for editing.
743     if ($tabs = $this->getDisplayTabs($view)) {
744       if ($display_id) {
745         $tabs[$display_id]['#active'] = TRUE;
746       }
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;
750     }
751
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] = [
755         '#type' => 'submit',
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],
764       ];
765     }
766
767     return $element;
768   }
769
770   /**
771    * Submit handler for form buttons that do not complete a form workflow.
772    *
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.
779    */
780   public function submitDelayDestination($form, FormStateInterface $form_state) {
781     $request = $this->requestStack->getCurrentRequest();
782     $destination = $request->query->get('destination');
783
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
787     // current request.
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);
792       }
793
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);
799       }
800
801       $form_state->setRedirectUrl($redirect);
802       $request->query->remove('destination');
803     }
804   }
805
806   /**
807    * Submit handler to duplicate a display for a view.
808    */
809   public function submitDisplayDuplicate($form, FormStateInterface $form_state) {
810     $view = $this->entity;
811     $display_id = $this->displayID;
812
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);
820
821     // By setting the current display the changed marker will appear on the new
822     // display.
823     $view->getExecutable()->current_display = $new_display_id;
824     $view->cacheSet();
825
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,
830     ]);
831   }
832
833   /**
834    * Submit handler to add a display to a view.
835    */
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
844     // display.
845     $view->getExecutable()->current_display = $display_id;
846     $view->cacheSet();
847
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,
852     ]);
853   }
854
855   /**
856    * Submit handler to Duplicate a display as another display type.
857    */
858   public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) {
859     /** @var \Drupal\views\ViewEntityInterface $view */
860     $view = $this->entity;
861     $display_id = $this->displayID;
862
863     // Create the new display.
864     $parents = $form_state->getTriggeringElement()['#parents'];
865     $display_type = array_pop($parents);
866
867     $new_display_id = $view->duplicateDisplayAsType($display_id, $display_type);
868
869     // By setting the current display the changed marker will appear on the new
870     // display.
871     $view->getExecutable()->current_display = $new_display_id;
872     $view->cacheSet();
873
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,
878     ]);
879   }
880
881   /**
882    * Build a renderable array representing one option on the edit form.
883    *
884    * This function might be more logical as a method on an object, if a suitable
885    * object emerges out of refactoring.
886    */
887   public function buildOptionForm(ViewUI $view, $id, $option, $display) {
888     $option_build = [];
889     $option_build['#theme'] = 'views_ui_display_tab_setting';
890
891     $option_build['#description'] = $option['title'];
892
893     $option_build['#link'] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
894
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);
899       }
900     }
901
902     if (!empty($view->getExecutable()->displayHandlers->get($display['id'])->options['defaults'][$id])) {
903       $display_id = 'default';
904       $option_build['#defaulted'] = TRUE;
905     }
906     else {
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;
911         }
912       }
913     }
914     $option_build['#attributes']['class'][] = Html::cleanCssIdentifier($display_id . '-' . $id);
915     return $option_build;
916   }
917
918   /**
919    * Add information about a section to a display.
920    */
921   public function getFormBucket(ViewUI $view, $type, $display) {
922     $executable = $view->getExecutable();
923     $executable->setDisplay($display['id']);
924     $executable->initStyle();
925
926     $types = $executable->getHandlerTypes();
927
928     $build = [
929       '#theme_wrappers' => ['views_ui_display_tab_bucket'],
930     ];
931
932     $build['#overridden'] = FALSE;
933     $build['#defaulted'] = FALSE;
934
935     $build['#name'] = $type;
936     $build['#title'] = $types[$type]['title'];
937
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';
940
941     // Different types now have different rearrange forms, so we use this switch
942     // to get the right one.
943     switch ($type) {
944       case 'filter':
945         // The rearrange form for filters contains the and/or UI, so override
946         // the used path.
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';
950         break;
951       case 'field':
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();
955         if (!$uses_fields) {
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']],
960           ];
961           return $build;
962         }
963         break;
964       case 'header':
965       case 'footer':
966       case 'empty':
967         if (!$executable->display_handler->usesAreas()) {
968           $build[$type][] = [
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']],
972           ];
973           return $build;
974         }
975         break;
976     }
977
978     // Create an array of actions to pass to links template.
979     $actions = [];
980     $count_handlers = count($executable->display_handler->getHandlers($type));
981
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']]);
984
985     $actions['add'] = [
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],
989     ];
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']]);
993
994       $actions['rearrange'] = [
995         'title' => $rearrange_text,
996         'url' => $rearrange_url,
997         'attributes' => ['class' => [$class, 'views-ajax-link'], 'id' => 'views-rearrange-' . $type],
998       ];
999     }
1000
1001     // Render the array of links
1002     $build['#actions'] = [
1003       '#type' => 'dropbutton',
1004       '#links' => $actions,
1005       '#attributes' => [
1006         'class' => ['views-ui-settings-bucket-operations'],
1007       ],
1008     ];
1009
1010     if (!$executable->display_handler->isDefaultDisplay()) {
1011       if (!$executable->display_handler->isDefaulted($types[$type]['plural'])) {
1012         $build['#overridden'] = TRUE;
1013       }
1014       else {
1015         $build['#defaulted'] = TRUE;
1016       }
1017     }
1018
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();
1025       }
1026     }
1027
1028     // Filters can now be grouped so we do a little bit extra:
1029     $groups = [];
1030     $grouping = FALSE;
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')) {
1037         $grouping = TRUE;
1038         $groups = [0 => []];
1039       }
1040     }
1041
1042     $build['fields'] = [];
1043
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';
1048
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', [
1054           'js' => 'nojs',
1055           'view' => $view->id(),
1056           'display_id' => $display['id'],
1057           'type' => $type,
1058           'id' => $id,
1059         ], ['attributes' => ['class' => ['views-ajax-link']]]));
1060         continue;
1061       }
1062
1063       $field_name = $handler->adminLabel(TRUE);
1064       if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
1065         $field_name = '(' . $relationships[$field['relationship']] . ') ' . $field_name;
1066       }
1067
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') . ']';
1075       }
1076       $build['fields'][$id]['#link'] = $this->l($link_text, new Url('views_ui.form_handler', [
1077         'js' => 'nojs',
1078         'view' => $view->id(),
1079         'display_id' => $display['id'],
1080         'type' => $type,
1081         'id' => $id,
1082       ], ['attributes' => $link_attributes]));
1083       $build['fields'][$id]['#class'][] = Html::cleanCssIdentifier($display['id'] . '-' . $type . '-' . $id);
1084
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', [
1087           'js' => 'nojs',
1088           'view' => $view->id(),
1089           'display_id' => $display['id'],
1090           'type' => $type,
1091           'id' => $id,
1092         ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Aggregation settings')]]));
1093       }
1094
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', [
1097           'js' => 'nojs',
1098           'view' => $view->id(),
1099           'display_id' => $display['id'],
1100           'type' => $type,
1101           'id' => $id,
1102         ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Settings')]]));
1103       }
1104
1105       if ($grouping) {
1106         $gid = $handler->options['group'];
1107
1108         // Show in default group if the group does not exist.
1109         if (empty($group_info['groups'][$gid])) {
1110           $gid = 0;
1111         }
1112         $groups[$gid][] = $id;
1113       }
1114     }
1115
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')),
1127           ];
1128         }
1129         // Display an operator between each pair of filters within the group.
1130         $keys = array_keys($contents);
1131         $last = end($keys);
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]);
1136           }
1137           $build['fields'][$pid] = $store[$pid];
1138         }
1139       }
1140     }
1141
1142     return $build;
1143   }
1144
1145 }