Upgraded drupal core with security updates
[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']) && $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);
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       elseif (isset($display->display['new_id'])) {
294         unset($display->display['new_id']);
295       }
296     }
297     $view->set('display', $displays);
298
299     // @todo: Revisit this when https://www.drupal.org/node/1668866 is in.
300     $query = $this->requestStack->getCurrentRequest()->query;
301     $destination = $query->get('destination');
302
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)) {
311           continue;
312         }
313
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');
317         }
318       }
319       // @todo Use Url::fromPath() once https://www.drupal.org/node/2351379 is
320       //   resolved.
321       $form_state->setRedirectUrl(Url::fromUri("base:$destination"));
322     }
323
324     $view->save();
325
326     drupal_set_message($this->t('The view %name has been saved.', ['%name' => $view->label()]));
327
328     // Remove this view from cache so we can edit it properly.
329     $this->tempStore->delete($view->id());
330   }
331
332   /**
333    * Form submission handler for the 'cancel' action.
334    *
335    * @param array $form
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.
339    */
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'));
345   }
346
347   /**
348    * Returns a renderable array representing the edit page for one display.
349    */
350   public function getDisplayTab($view) {
351     $build = [];
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
355     // page.
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']]);
359     }
360     // Build the content of the edit page.
361     else {
362       $build['details'] = $this->getDisplayDetails($view, $display->display);
363     }
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);
367     return $build;
368   }
369
370   /**
371    * Helper function to get the display details section of the edit UI.
372    *
373    * @param $display
374    *
375    * @return array
376    *   A renderable page build array.
377    */
378   public function getDisplayDetails($view, $display) {
379     $display_title = $this->getDisplayLabel($view, $display['id'], FALSE);
380     $build = [
381       '#theme_wrappers' => ['container'],
382       '#attributes' => ['id' => 'edit-display-settings-details'],
383     ];
384
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();
390
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'];
395
396       // The Delete, Duplicate and Undo Delete buttons.
397       $build['top']['actions'] = [
398         '#theme_wrappers' => ['dropbutton_wrapper'],
399       ];
400
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">';
404
405       if (!$is_display_deleted) {
406         if (!$is_enabled) {
407           $build['top']['actions']['enable'] = [
408             '#type' => 'submit',
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>',
414           ];
415         }
416         // Add a link to view the page unless the view is disabled or has no
417         // path.
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, '/'));
425             }
426             else {
427               $url = Url::fromUri("base:$path");
428             }
429             $build['top']['actions']['path'] = [
430               '#type' => 'link',
431               '#title' => $this->t('View @display_title', ['@display_title' => $display_title]),
432               '#options' => ['alt' => [$this->t("Go to the real page for this display")]],
433               '#url' => $url,
434               '#prefix' => '<li class="view">',
435               "#suffix" => '</li>',
436             ];
437           }
438         }
439         if (!$is_default) {
440           $build['top']['actions']['duplicate'] = [
441             '#type' => 'submit',
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>',
447           ];
448         }
449         // Always allow a display to be deleted.
450         $build['top']['actions']['delete'] = [
451           '#type' => 'submit',
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>',
457         ];
458
459         foreach (Views::fetchPluginNames('display', NULL, [$view->get('storage')->get('base_table')]) as $type => $label) {
460           if ($type == $display['display_plugin']) {
461             continue;
462           }
463
464           $build['top']['actions']['duplicate_as'][$type] = [
465             '#type' => 'submit',
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>',
471           ];
472         }
473       }
474       else {
475         $build['top']['actions']['undo_delete'] = [
476           '#type' => 'submit',
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>',
482         ];
483       }
484       if ($is_enabled) {
485         $build['top']['actions']['disable'] = [
486           '#type' => 'submit',
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>',
492         ];
493       }
494       $build['top']['actions']['suffix']['#markup'] = '</ul>';
495
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'),
501       ];
502     }
503
504     $build['columns'] = [];
505     $build['columns']['#theme_wrappers'] = ['container'];
506     $build['columns']['#attributes'] = ['id' => 'edit-display-settings-main', 'class' => ['clearfix', 'views-display-columns']];
507
508     $build['columns']['first']['#theme_wrappers'] = ['container'];
509     $build['columns']['first']['#attributes'] = ['class' => ['views-display-column', 'first']];
510
511     $build['columns']['second']['#theme_wrappers'] = ['container'];
512     $build['columns']['second']['#attributes'] = ['class' => ['views-display-column', 'second']];
513
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'] = [];
519
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'],
525       '#attributes' => [
526         'class' => [
527           'views-display-column',
528           'third',
529         ],
530       ],
531     ];
532     // Collapse the details by default.
533     $build['columns']['third']['#open'] = \Drupal::config('views.settings')->get('ui.show.advanced_column');
534
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).
537     $buckets = [];
538
539     // Fetch options from the display plugin, with a list of buckets they go into.
540     $options = [];
541     $view->getExecutable()->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
542
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);
547     }
548
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'];
554       }
555       // If a bucket doesn't pick one of our predefined columns to belong to, put
556       // it in the last one.
557       else {
558         $column = 'third';
559       }
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;
565       }
566     }
567
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);
576
577     return $build;
578   }
579
580   /**
581    * Submit handler to add a restore a removed display to a view.
582    */
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);
590
591     // Store in cache
592     $view->cacheSet();
593
594     // Redirect to the top-level edit page.
595     $form_state->setRedirect('entity.view.edit_display_form', [
596       'view' => $view->id(),
597       'display_id' => $id,
598     ]);
599   }
600
601   /**
602    * Submit handler to enable a disabled display.
603    */
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);
609
610     // Store in cache
611     $view->cacheSet();
612
613     // Redirect to the top-level edit page.
614     $form_state->setRedirect('entity.view.edit_display_form', [
615       'view' => $view->id(),
616       'display_id' => $id,
617     ]);
618   }
619
620   /**
621    * Submit handler to disable display.
622    */
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);
627
628     // Store in cache
629     $view->cacheSet();
630
631     // Redirect to the top-level edit page.
632     $form_state->setRedirect('entity.view.edit_display_form', [
633       'view' => $view->id(),
634       'display_id' => $id,
635     ]);
636   }
637
638   /**
639    * Submit handler to delete a display from a view.
640    */
641   public function submitDisplayDelete($form, FormStateInterface $form_state) {
642     $view = $this->entity;
643     $display_id = $form_state->get('display_id');
644
645     // Mark the display for deletion.
646     $displays = $view->get('display');
647     $displays[$display_id]['deleted'] = TRUE;
648     $view->set('display', $displays);
649     $view->cacheSet();
650
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'));
654   }
655
656   /**
657    * Regenerate the current tab for AJAX updates.
658    *
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.
665    */
666   public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
667     $this->displayID = $display_id;
668     if (!$view->getExecutable()->setDisplay('default')) {
669       return;
670     }
671
672     // Regenerate the main display area.
673     $build = $this->getDisplayTab($view);
674     $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, $build));
675
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));
679   }
680
681   /**
682    * Render the top of the display so it can be updated during ajax operations.
683    */
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'];
689
690     // Extra actions for the display
691     $element['extra_actions'] = [
692       '#type' => 'dropbutton',
693       '#attributes' => [
694         'id' => 'views-display-extra-actions',
695       ],
696       '#links' => [
697         'edit-details' => [
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']],
701         ],
702         'analyze' => [
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']],
706         ],
707         'duplicate' => [
708           'title' => $this->t('Duplicate view'),
709           'url' => $view->urlInfo('duplicate-form'),
710         ],
711         'reorder' => [
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']],
715         ],
716       ],
717     ];
718
719     if ($view->access('delete')) {
720       $element['extra_actions']['#links']['delete'] = [
721         'title' => $this->t('Delete view'),
722         'url' => $view->urlInfo('delete-form'),
723       ];
724     }
725
726     // Let other modules add additional links here.
727     \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
728
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')],
735         ];
736       }
737       else {
738         $element['extra_actions']['#links']['delete'] = [
739           'title' => $this->t('Delete view'),
740           'url' => $view->urlInfo('delete-form'),
741         ];
742       }
743     }
744
745     // Determine the displays available for editing.
746     if ($tabs = $this->getDisplayTabs($view)) {
747       if ($display_id) {
748         $tabs[$display_id]['#active'] = TRUE;
749       }
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;
753     }
754
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] = [
758         '#type' => 'submit',
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],
767       ];
768     }
769
770     return $element;
771   }
772
773   /**
774    * Submit handler for form buttons that do not complete a form workflow.
775    *
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.
782    */
783   public function submitDelayDestination($form, FormStateInterface $form_state) {
784     $request = $this->requestStack->getCurrentRequest();
785     $destination = $request->query->get('destination');
786
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
790     // current request.
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);
795       }
796
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);
802       }
803
804       $form_state->setRedirectUrl($redirect);
805       $request->query->remove('destination');
806     }
807   }
808
809   /**
810    * Submit handler to duplicate a display for a view.
811    */
812   public function submitDisplayDuplicate($form, FormStateInterface $form_state) {
813     $view = $this->entity;
814     $display_id = $this->displayID;
815
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);
823
824     // By setting the current display the changed marker will appear on the new
825     // display.
826     $view->getExecutable()->current_display = $new_display_id;
827     $view->cacheSet();
828
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,
833     ]);
834   }
835
836   /**
837    * Submit handler to add a display to a view.
838    */
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
847     // display.
848     $view->getExecutable()->current_display = $display_id;
849     $view->cacheSet();
850
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,
855     ]);
856   }
857
858   /**
859    * Submit handler to Duplicate a display as another display type.
860    */
861   public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) {
862     /** @var \Drupal\views\ViewEntityInterface $view */
863     $view = $this->entity;
864     $display_id = $this->displayID;
865
866     // Create the new display.
867     $parents = $form_state->getTriggeringElement()['#parents'];
868     $display_type = array_pop($parents);
869
870     $new_display_id = $view->duplicateDisplayAsType($display_id, $display_type);
871
872     // By setting the current display the changed marker will appear on the new
873     // display.
874     $view->getExecutable()->current_display = $new_display_id;
875     $view->cacheSet();
876
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,
881     ]);
882   }
883
884   /**
885    * Build a renderable array representing one option on the edit form.
886    *
887    * This function might be more logical as a method on an object, if a suitable
888    * object emerges out of refactoring.
889    */
890   public function buildOptionForm(ViewUI $view, $id, $option, $display) {
891     $option_build = [];
892     $option_build['#theme'] = 'views_ui_display_tab_setting';
893
894     $option_build['#description'] = $option['title'];
895
896     $option_build['#link'] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
897
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);
902       }
903     }
904
905     if (!empty($view->getExecutable()->displayHandlers->get($display['id'])->options['defaults'][$id])) {
906       $display_id = 'default';
907       $option_build['#defaulted'] = TRUE;
908     }
909     else {
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;
914         }
915       }
916     }
917     $option_build['#attributes']['class'][] = Html::cleanCssIdentifier($display_id . '-' . $id);
918     return $option_build;
919   }
920
921   /**
922    * Add information about a section to a display.
923    */
924   public function getFormBucket(ViewUI $view, $type, $display) {
925     $executable = $view->getExecutable();
926     $executable->setDisplay($display['id']);
927     $executable->initStyle();
928
929     $types = $executable->getHandlerTypes();
930
931     $build = [
932       '#theme_wrappers' => ['views_ui_display_tab_bucket'],
933     ];
934
935     $build['#overridden'] = FALSE;
936     $build['#defaulted'] = FALSE;
937
938     $build['#name'] = $type;
939     $build['#title'] = $types[$type]['title'];
940
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';
943
944     // Different types now have different rearrange forms, so we use this switch
945     // to get the right one.
946     switch ($type) {
947       case 'filter':
948         // The rearrange form for filters contains the and/or UI, so override
949         // the used path.
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';
953         break;
954       case 'field':
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();
958         if (!$uses_fields) {
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']],
963           ];
964           return $build;
965         }
966         break;
967       case 'header':
968       case 'footer':
969       case 'empty':
970         if (!$executable->display_handler->usesAreas()) {
971           $build[$type][] = [
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']],
975           ];
976           return $build;
977         }
978         break;
979     }
980
981     // Create an array of actions to pass to links template.
982     $actions = [];
983     $count_handlers = count($executable->display_handler->getHandlers($type));
984
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']]);
987
988     $actions['add'] = [
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],
992     ];
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']]);
996
997       $actions['rearrange'] = [
998         'title' => $rearrange_text,
999         'url' => $rearrange_url,
1000         'attributes' => ['class' => [$class, 'views-ajax-link'], 'id' => 'views-rearrange-' . $type],
1001       ];
1002     }
1003
1004     // Render the array of links
1005     $build['#actions'] = [
1006       '#type' => 'dropbutton',
1007       '#links' => $actions,
1008       '#attributes' => [
1009         'class' => ['views-ui-settings-bucket-operations'],
1010       ],
1011     ];
1012
1013     if (!$executable->display_handler->isDefaultDisplay()) {
1014       if (!$executable->display_handler->isDefaulted($types[$type]['plural'])) {
1015         $build['#overridden'] = TRUE;
1016       }
1017       else {
1018         $build['#defaulted'] = TRUE;
1019       }
1020     }
1021
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();
1028       }
1029     }
1030
1031     // Filters can now be grouped so we do a little bit extra:
1032     $groups = [];
1033     $grouping = FALSE;
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')) {
1040         $grouping = TRUE;
1041         $groups = [0 => []];
1042       }
1043     }
1044
1045     $build['fields'] = [];
1046
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';
1051
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', [
1057           'js' => 'nojs',
1058           'view' => $view->id(),
1059           'display_id' => $display['id'],
1060           'type' => $type,
1061           'id' => $id,
1062         ], ['attributes' => ['class' => ['views-ajax-link']]]));
1063         continue;
1064       }
1065
1066       $field_name = $handler->adminLabel(TRUE);
1067       if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
1068         $field_name = '(' . $relationships[$field['relationship']] . ') ' . $field_name;
1069       }
1070
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') . ']';
1078       }
1079       $build['fields'][$id]['#link'] = $this->l($link_text, new Url('views_ui.form_handler', [
1080         'js' => 'nojs',
1081         'view' => $view->id(),
1082         'display_id' => $display['id'],
1083         'type' => $type,
1084         'id' => $id,
1085       ], ['attributes' => $link_attributes]));
1086       $build['fields'][$id]['#class'][] = Html::cleanCssIdentifier($display['id'] . '-' . $type . '-' . $id);
1087
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', [
1090           'js' => 'nojs',
1091           'view' => $view->id(),
1092           'display_id' => $display['id'],
1093           'type' => $type,
1094           'id' => $id,
1095         ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Aggregation settings')]]));
1096       }
1097
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', [
1100           'js' => 'nojs',
1101           'view' => $view->id(),
1102           'display_id' => $display['id'],
1103           'type' => $type,
1104           'id' => $id,
1105         ], ['attributes' => ['class' => ['views-button-configure', 'views-ajax-link'], 'title' => $this->t('Settings')]]));
1106       }
1107
1108       if ($grouping) {
1109         $gid = $handler->options['group'];
1110
1111         // Show in default group if the group does not exist.
1112         if (empty($group_info['groups'][$gid])) {
1113           $gid = 0;
1114         }
1115         $groups[$gid][] = $id;
1116       }
1117     }
1118
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')),
1130           ];
1131         }
1132         // Display an operator between each pair of filters within the group.
1133         $keys = array_keys($contents);
1134         $last = end($keys);
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]);
1139           }
1140           $build['fields'][$pid] = $store[$pid];
1141         }
1142       }
1143     }
1144
1145     return $build;
1146   }
1147
1148 }