badfdbe3d27b02d0a86e9832e62f023cda36528e
[yaffs-website] / web / core / modules / views / src / Plugin / views / wizard / WizardPluginBase.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\wizard;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Entity\EntityPublishedInterface;
7 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Routing\UrlGeneratorTrait;
10 use Drupal\views\Entity\View;
11 use Drupal\views\Views;
12 use Drupal\views_ui\ViewUI;
13 use Drupal\views\Plugin\views\display\DisplayPluginBase;
14 use Drupal\views\Plugin\views\PluginBase;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
16
17 /**
18  * @defgroup views_wizard_plugins Views wizard plugins
19  * @{
20  * Plugins for Views wizards.
21  *
22  * Wizard handlers implement \Drupal\views\Plugin\views\wizard\WizardInterface,
23  * and usually extend \Drupal\views\Plugin\views\wizard\WizardPluginBase. They
24  * must be annotated with \Drupal\views\Annotation\ViewsWizard annotation,
25  * and they must be in namespace directory Plugin\views\wizard.
26  *
27  * @ingroup views_plugins
28  * @see plugin_api
29  */
30
31 /**
32  * Base class for Views wizard plugins.
33  *
34  * This is a very generic Views Wizard class that can be constructed for any
35  * base table.
36  */
37 abstract class WizardPluginBase extends PluginBase implements WizardInterface {
38
39   use UrlGeneratorTrait;
40
41   /**
42    * The base table connected with the wizard.
43    *
44    * @var string
45    */
46   protected $base_table;
47
48   /**
49    * The entity type connected with the wizard.
50    *
51    * There might be base tables connected with entity types, if not this would
52    * be empty.
53    *
54    * @var string
55    */
56   protected $entityTypeId;
57
58   /**
59    * Contains the information from entity_get_info of the $entity_type.
60    *
61    * @var \Drupal\Core\Entity\EntityTypeInterface
62    */
63   protected $entityType;
64
65   /**
66    * An array of validated view objects, keyed by a hash.
67    *
68    * @var array
69    */
70   protected $validated_views = [];
71
72   /**
73    * The table column used for sorting by create date of this wizard.
74    *
75    * @var string
76    */
77   protected $createdColumn;
78
79   /**
80    * Views items configuration arrays for filters added by the wizard.
81    *
82    * @var array
83    */
84   protected $filters = [];
85
86   /**
87    * Views items configuration arrays for sorts added by the wizard.
88    *
89    * @var array
90    */
91   protected $sorts = [];
92
93   /**
94    * The available store criteria.
95    *
96    * @var array
97    */
98   protected $availableSorts = [];
99
100   /**
101    * Default values for filters.
102    *
103    * By default, filters are not exposed and added to the first non-reserved
104    * filter group.
105    *
106    * @var array
107    */
108   protected $filter_defaults = [
109     'id' => NULL,
110     'expose' => ['operator' => FALSE],
111     'group' => 1,
112   ];
113
114   /**
115    * The bundle info service.
116    *
117    * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
118    */
119   protected $bundleInfoService;
120
121   /**
122    * {@inheritdoc}
123    */
124   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
125     return new static(
126       $configuration,
127       $plugin_id,
128       $plugin_definition,
129       $container->get('entity_type.bundle.info')
130     );
131   }
132
133   /**
134    * Constructs a WizardPluginBase object.
135    */
136   public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeBundleInfoInterface $bundle_info_service) {
137     parent::__construct($configuration, $plugin_id, $plugin_definition);
138
139     $this->bundleInfoService = $bundle_info_service;
140     $this->base_table = $this->definition['base_table'];
141
142     $entity_types = \Drupal::entityManager()->getDefinitions();
143     foreach ($entity_types as $entity_type_id => $entity_type) {
144       if (in_array($this->base_table, [$entity_type->getBaseTable(), $entity_type->getDataTable(), $entity_type->getRevisionTable(), $entity_type->getRevisionDataTable()], TRUE)) {
145         $this->entityType = $entity_type;
146         $this->entityTypeId = $entity_type_id;
147       }
148     }
149   }
150
151   /**
152    * Gets the createdColumn property.
153    *
154    * @return string
155    *   The name of the column containing the created date.
156    */
157   public function getCreatedColumn() {
158     return $this->createdColumn;
159   }
160
161   /**
162    * Gets the filters property.
163    *
164    * @return array
165    */
166   public function getFilters() {
167     $filters = [];
168
169     // Add a default filter on the publishing status field, if available.
170     if ($this->entityType && is_subclass_of($this->entityType->getClass(), EntityPublishedInterface::class)) {
171       $field_name = $this->entityType->getKey('published');
172       $this->filters = [
173         $field_name => [
174           'value' => TRUE,
175           'table' => $this->base_table,
176           'field' => $field_name,
177           'plugin_id' => 'boolean',
178           'entity_type' => $this->entityTypeId,
179           'entity_field' => $field_name,
180         ],
181       ] + $this->filters;
182     }
183
184     $default = $this->filter_defaults;
185
186     foreach ($this->filters as $name => $info) {
187       $default['id'] = $name;
188       $filters[$name] = $info + $default;
189     }
190
191     return $filters;
192   }
193
194   /**
195    * Gets the availableSorts property.
196    *
197    * @return array
198    */
199   public function getAvailableSorts() {
200     return $this->availableSorts;
201   }
202
203   /**
204    * Gets the sorts property.
205    *
206    * @return array
207    */
208   public function getSorts() {
209     return $this->sorts;
210   }
211
212   /**
213    * {@inheritdoc}
214    */
215   public function buildForm(array $form, FormStateInterface $form_state) {
216     $style_options = Views::fetchPluginNames('style', 'normal', [$this->base_table]);
217     $feed_row_options = Views::fetchPluginNames('row', 'feed', [$this->base_table]);
218     $path_prefix = $this->url('<none>', [], ['absolute' => TRUE]);
219
220     // Add filters and sorts which apply to the view as a whole.
221     $this->buildFilters($form, $form_state);
222     $this->buildSorts($form, $form_state);
223
224     $form['displays']['page'] = [
225       '#type' => 'fieldset',
226       '#title' => $this->t('Page settings'),
227       '#attributes' => ['class' => ['views-attachment', 'fieldset-no-legend']],
228       '#tree' => TRUE,
229     ];
230     $form['displays']['page']['create'] = [
231       '#title' => $this->t('Create a page'),
232       '#type' => 'checkbox',
233       '#attributes' => ['class' => ['strong']],
234       '#default_value' => FALSE,
235       '#id' => 'edit-page-create',
236     ];
237
238     // All options for the page display are included in this container so they
239     // can be hidden as a group when the "Create a page" checkbox is unchecked.
240     $form['displays']['page']['options'] = [
241       '#type' => 'container',
242       '#attributes' => ['class' => ['options-set']],
243       '#states' => [
244         'visible' => [
245           ':input[name="page[create]"]' => ['checked' => TRUE],
246         ],
247       ],
248       '#prefix' => '<div><div id="edit-page-wrapper">',
249       '#suffix' => '</div></div>',
250       '#parents' => ['page'],
251     ];
252
253     $form['displays']['page']['options']['title'] = [
254       '#title' => $this->t('Page title'),
255       '#type' => 'textfield',
256       '#maxlength' => 255,
257     ];
258     $form['displays']['page']['options']['path'] = [
259       '#title' => $this->t('Path'),
260       '#type' => 'textfield',
261       '#field_prefix' => $path_prefix,
262       // Account for the leading backslash.
263       '#maxlength' => 254,
264     ];
265     $form['displays']['page']['options']['style'] = [
266       '#type' => 'fieldset',
267       '#title' => $this->t('Page display settings'),
268       '#attributes' => ['class' => ['container-inline', 'fieldset-no-legend']],
269     ];
270
271     // Create the dropdown for choosing the display format.
272     $form['displays']['page']['options']['style']['style_plugin'] = [
273       '#title' => $this->t('Display format'),
274       '#type' => 'select',
275       '#options' => $style_options,
276     ];
277     $style_form = &$form['displays']['page']['options']['style'];
278     $style_form['style_plugin']['#default_value'] = static::getSelected($form_state, ['page', 'style', 'style_plugin'], 'default', $style_form['style_plugin']);
279     // Changing this dropdown updates $form['displays']['page']['options'] via
280     // AJAX.
281     views_ui_add_ajax_trigger($style_form, 'style_plugin', ['displays', 'page', 'options']);
282
283     $this->buildFormStyle($form, $form_state, 'page');
284     $form['displays']['page']['options']['items_per_page'] = [
285       '#title' => $this->t('Items to display'),
286       '#type' => 'number',
287       '#default_value' => 10,
288       '#min' => 0,
289     ];
290     $form['displays']['page']['options']['pager'] = [
291       '#title' => $this->t('Use a pager'),
292       '#type' => 'checkbox',
293       '#default_value' => TRUE,
294     ];
295     $form['displays']['page']['options']['link'] = [
296       '#title' => $this->t('Create a menu link'),
297       '#type' => 'checkbox',
298       '#id' => 'edit-page-link',
299     ];
300     $form['displays']['page']['options']['link_properties'] = [
301       '#type' => 'container',
302       '#states' => [
303         'visible' => [
304           ':input[name="page[link]"]' => ['checked' => TRUE],
305         ],
306       ],
307       '#prefix' => '<div id="edit-page-link-properties-wrapper">',
308       '#suffix' => '</div>',
309     ];
310     if (\Drupal::moduleHandler()->moduleExists('menu_ui')) {
311       $menu_options = menu_ui_get_menus();
312     }
313     else {
314       // These are not yet translated.
315       $menu_options = menu_list_system_menus();
316       foreach ($menu_options as $name => $title) {
317         $menu_options[$name] = $this->t($title);
318       }
319     }
320     $form['displays']['page']['options']['link_properties']['menu_name'] = [
321       '#title' => $this->t('Menu'),
322       '#type' => 'select',
323       '#options' => $menu_options,
324     ];
325     $form['displays']['page']['options']['link_properties']['title'] = [
326       '#title' => $this->t('Link text'),
327       '#type' => 'textfield',
328     ];
329     // Only offer a feed if we have at least one available feed row style.
330     if ($feed_row_options) {
331       $form['displays']['page']['options']['feed'] = [
332         '#title' => $this->t('Include an RSS feed'),
333         '#type' => 'checkbox',
334         '#id' => 'edit-page-feed',
335       ];
336       $form['displays']['page']['options']['feed_properties'] = [
337         '#type' => 'container',
338         '#states' => [
339           'visible' => [
340             ':input[name="page[feed]"]' => ['checked' => TRUE],
341           ],
342         ],
343         '#prefix' => '<div id="edit-page-feed-properties-wrapper">',
344         '#suffix' => '</div>',
345       ];
346       $form['displays']['page']['options']['feed_properties']['path'] = [
347         '#title' => $this->t('Feed path'),
348         '#type' => 'textfield',
349         '#field_prefix' => $path_prefix,
350         // Account for the leading backslash.
351         '#maxlength' => 254,
352       ];
353       // This will almost never be visible.
354       $form['displays']['page']['options']['feed_properties']['row_plugin'] = [
355         '#title' => $this->t('Feed row style'),
356         '#type' => 'select',
357         '#options' => $feed_row_options,
358         '#default_value' => key($feed_row_options),
359         '#access' => (count($feed_row_options) > 1),
360         '#states' => [
361           'visible' => [
362             ':input[name="page[feed]"]' => ['checked' => TRUE],
363           ],
364         ],
365         '#prefix' => '<div id="edit-page-feed-properties-row-plugin-wrapper">',
366         '#suffix' => '</div>',
367       ];
368     }
369
370     // Only offer the block settings if the module is enabled.
371     if (\Drupal::moduleHandler()->moduleExists('block')) {
372       $form['displays']['block'] = [
373         '#type' => 'fieldset',
374         '#title' => $this->t('Block settings'),
375         '#attributes' => ['class' => ['views-attachment', 'fieldset-no-legend']],
376         '#tree' => TRUE,
377       ];
378       $form['displays']['block']['create'] = [
379         '#title' => $this->t('Create a block'),
380         '#type' => 'checkbox',
381         '#attributes' => ['class' => ['strong']],
382         '#id' => 'edit-block-create',
383       ];
384
385       // All options for the block display are included in this container so
386       // they can be hidden as a group when the "Create a block" checkbox is
387       // unchecked.
388       $form['displays']['block']['options'] = [
389         '#type' => 'container',
390         '#attributes' => ['class' => ['options-set']],
391         '#states' => [
392           'visible' => [
393             ':input[name="block[create]"]' => ['checked' => TRUE],
394           ],
395         ],
396         '#prefix' => '<div id="edit-block-wrapper">',
397         '#suffix' => '</div>',
398         '#parents' => ['block'],
399       ];
400
401       $form['displays']['block']['options']['title'] = [
402         '#title' => $this->t('Block title'),
403         '#type' => 'textfield',
404         '#maxlength' => 255,
405       ];
406       $form['displays']['block']['options']['style'] = [
407         '#type' => 'fieldset',
408         '#title' => $this->t('Block display settings'),
409         '#attributes' => ['class' => ['container-inline', 'fieldset-no-legend']],
410       ];
411
412       // Create the dropdown for choosing the display format.
413       $form['displays']['block']['options']['style']['style_plugin'] = [
414         '#title' => $this->t('Display format'),
415         '#type' => 'select',
416         '#options' => $style_options,
417       ];
418       $style_form = &$form['displays']['block']['options']['style'];
419       $style_form['style_plugin']['#default_value'] = static::getSelected($form_state, ['block', 'style', 'style_plugin'], 'default', $style_form['style_plugin']);
420       // Changing this dropdown updates $form['displays']['block']['options']
421       // via AJAX.
422       views_ui_add_ajax_trigger($style_form, 'style_plugin', ['displays', 'block', 'options']);
423
424       $this->buildFormStyle($form, $form_state, 'block');
425       $form['displays']['block']['options']['items_per_page'] = [
426         '#title' => $this->t('Items per block'),
427         '#type' => 'number',
428         '#default_value' => 5,
429         '#min' => 0,
430       ];
431       $form['displays']['block']['options']['pager'] = [
432         '#title' => $this->t('Use a pager'),
433         '#type' => 'checkbox',
434         '#default_value' => FALSE,
435       ];
436     }
437
438     // Only offer the REST export settings if the module is enabled.
439     if (\Drupal::moduleHandler()->moduleExists('rest')) {
440       $form['displays']['rest_export'] = [
441         '#type' => 'fieldset',
442         '#title' => $this->t('REST export settings'),
443         '#attributes' => ['class' => ['views-attachment', 'fieldset-no-legend']],
444         '#tree' => TRUE,
445       ];
446       $form['displays']['rest_export']['create'] = [
447         '#title' => $this->t('Provide a REST export'),
448         '#type' => 'checkbox',
449         '#attributes' => ['class' => ['strong']],
450         '#id' => 'edit-rest-export-create',
451       ];
452
453       // All options for the REST export display are included in this container
454       // so they can be hidden as a group when the "Provide a REST export"
455       // checkbox is unchecked.
456       $form['displays']['rest_export']['options'] = [
457         '#type' => 'container',
458         '#attributes' => ['class' => ['options-set']],
459         '#states' => [
460           'visible' => [
461             ':input[name="rest_export[create]"]' => ['checked' => TRUE],
462           ],
463         ],
464         '#prefix' => '<div id="edit-rest-export-wrapper">',
465         '#suffix' => '</div>',
466         '#parents' => ['rest_export'],
467       ];
468
469       $form['displays']['rest_export']['options']['path'] = [
470         '#title' => $this->t('REST export path'),
471         '#type' => 'textfield',
472         '#field_prefix' => $path_prefix,
473         // Account for the leading backslash.
474         '#maxlength' => 254,
475       ];
476     }
477
478     return $form;
479   }
480
481   /**
482    * Gets the current value of a #select element, from within a form constructor function.
483    *
484    * This function is intended for use in highly dynamic forms (in particular the
485    * add view wizard) which are rebuilt in different ways depending on which
486    * triggering element (AJAX or otherwise) was most recently fired. For example,
487    * sometimes it is necessary to decide how to build one dynamic form element
488    * based on the value of a different dynamic form element that may not have
489    * even been present on the form the last time it was submitted. This function
490    * takes care of resolving those conflicts and gives you the proper current
491    * value of the requested #select element.
492    *
493    * By necessity, this function sometimes uses non-validated user input from
494    * FormState::$input in making its determination. Although it performs some
495    * minor validation of its own, it is not complete. The intention is that the
496    * return value of this function should only be used to help decide how to
497    * build the current form the next time it is reloaded, not to be saved as if
498    * it had gone through the normal, final form validation process. Do NOT use
499    * the results of this function for any other purpose besides deciding how to
500    * build the next version of the form.
501    *
502    * @param \Drupal\Core\Form\FormStateInterface $form_state
503    *   The current state of the form.
504    * @param $parents
505    *   An array of parent keys that point to the part of the submitted form
506    *   values that are expected to contain the element's value (in the case where
507    *   this form element was actually submitted). In a simple case (assuming
508    *   #tree is TRUE throughout the form), if the select element is located in
509    *   $form['wrapper']['select'], so that the submitted form values would
510    *   normally be found in $form_state->getValue(array('wrapper', 'select')),
511    *   you would pass array('wrapper', 'select') for this parameter.
512    * @param $default_value
513    *   The default value to return if the #select element does not currently have
514    *   a proper value set based on the submitted input.
515    * @param $element
516    *   An array representing the current version of the #select element within
517    *   the form.
518    *
519    * @return
520    *   The current value of the #select element. A common use for this is to feed
521    *   it back into $element['#default_value'] so that the form will be rendered
522    *   with the correct value selected.
523    */
524   public static function getSelected(FormStateInterface $form_state, $parents, $default_value, $element) {
525     // For now, don't trust this to work on anything but a #select element.
526     if (!isset($element['#type']) || $element['#type'] != 'select' || !isset($element['#options'])) {
527       return $default_value;
528     }
529
530     // If there is a user-submitted value for this element that matches one of
531     // the currently available options attached to it, use that. However, only
532     // perform this check during the form rebuild. During the initial build
533     // after #ajax is triggered, we need to rebuild the form as it was
534     // initially. We need to check FormState::getUserInput() rather than
535     // $form_state->getValues() here because the triggering element often has
536     // the #limit_validation_errors property set to prevent unwanted errors
537     // elsewhere on the form. This means that the $form_state->getValues() array
538     // won't be complete. We could make it complete by adding each required part
539     // of the form to the #limit_validation_errors property individually as the
540     // form is being built, but this is difficult to do for a highly dynamic and
541     // extensible form. This method is much simpler.
542     $user_input = $form_state->isRebuilding() ? $form_state->getUserInput() : [];
543     if (!empty($user_input)) {
544       $key_exists = NULL;
545       $submitted = NestedArray::getValue($user_input, $parents, $key_exists);
546       // Check that the user-submitted value is one of the allowed options before
547       // returning it. This is not a substitute for actual form validation;
548       // rather it is necessary because, for example, the same select element
549       // might have #options A, B, and C under one set of conditions but #options
550       // D, E, F under a different set of conditions. So the form submission
551       // might have occurred with option A selected, but when the form is rebuilt
552       // option A is no longer one of the choices. In that case, we don't want to
553       // use the value that was submitted anymore but rather fall back to the
554       // default value.
555       if ($key_exists && in_array($submitted, array_keys($element['#options']))) {
556         return $submitted;
557       }
558     }
559
560     // Fall back on returning the default value if nothing was returned above.
561     return $default_value;
562   }
563
564   /**
565    * Adds the style options to the wizard form.
566    *
567    * @param array $form
568    *   The full wizard form array.
569    * @param \Drupal\Core\Form\FormStateInterface $form_state
570    *   The current state of the wizard form.
571    * @param string $type
572    *   The display ID (e.g. 'page' or 'block').
573    */
574   protected function buildFormStyle(array &$form, FormStateInterface $form_state, $type) {
575     $style_form = &$form['displays'][$type]['options']['style'];
576     $style = $style_form['style_plugin']['#default_value'];
577     $style_plugin = Views::pluginManager('style')->createInstance($style);
578     if (isset($style_plugin) && $style_plugin->usesRowPlugin()) {
579       $options = $this->rowStyleOptions();
580       $style_form['row_plugin'] = [
581         '#type' => 'select',
582         '#title' => $this->t('of'),
583         '#options' => $options,
584         '#access' => count($options) > 1,
585       ];
586       // For the block display, the default value should be "titles (linked)",
587       // if it's available (since that's the most common use case).
588       $block_with_linked_titles_available = ($type == 'block' && isset($options['titles_linked']));
589       $default_value = $block_with_linked_titles_available ? 'titles_linked' : key($options);
590       $style_form['row_plugin']['#default_value'] = static::getSelected($form_state, [$type, 'style', 'row_plugin'], $default_value, $style_form['row_plugin']);
591       // Changing this dropdown updates the individual row options via AJAX.
592       views_ui_add_ajax_trigger($style_form, 'row_plugin', ['displays', $type, 'options', 'style', 'row_options']);
593
594       // This is the region that can be updated by AJAX. The base class doesn't
595       // add anything here, but child classes can.
596       $style_form['row_options'] = [
597         '#theme_wrappers' => ['container'],
598       ];
599     }
600     elseif ($style_plugin->usesFields()) {
601       $style_form['row_plugin'] = ['#markup' => '<span>' . $this->t('of fields') . '</span>'];
602     }
603   }
604
605   /**
606    * Retrieves row style plugin names.
607    *
608    * @return array
609    *   Returns the plugin names available for the base table of the wizard.
610    */
611   protected function rowStyleOptions() {
612     // Get all available row plugins by default.
613     $options = Views::fetchPluginNames('row', 'normal', [$this->base_table]);
614     return $options;
615   }
616
617   /**
618    * Builds the form structure for selecting the view's filters.
619    *
620    * By default, this adds "of type" and "tagged with" filters (when they are
621    * available).
622    */
623   protected function buildFilters(&$form, FormStateInterface $form_state) {
624     module_load_include('inc', 'views_ui', 'admin');
625
626     $bundles = $this->bundleInfoService->getBundleInfo($this->entityTypeId);
627     // If the current base table support bundles and has more than one (like user).
628     if (!empty($bundles) && $this->entityType && $this->entityType->hasKey('bundle')) {
629       // Get all bundles and their human readable names.
630       $options = ['all' => $this->t('All')];
631       foreach ($bundles as $type => $bundle) {
632         $options[$type] = $bundle['label'];
633       }
634       $form['displays']['show']['type'] = [
635         '#type' => 'select',
636         '#title' => $this->t('of type'),
637         '#options' => $options,
638       ];
639       $selected_bundle = static::getSelected($form_state, ['show', 'type'], 'all', $form['displays']['show']['type']);
640       $form['displays']['show']['type']['#default_value'] = $selected_bundle;
641       // Changing this dropdown updates the entire content of $form['displays']
642       // via AJAX, since each bundle might have entirely different fields
643       // attached to it, etc.
644       views_ui_add_ajax_trigger($form['displays']['show'], 'type', ['displays']);
645     }
646   }
647
648   /**
649    * Builds the form structure for selecting the view's sort order.
650    *
651    * By default, this adds a "sorted by [date]" filter (when it is available).
652    */
653   protected function buildSorts(&$form, FormStateInterface $form_state) {
654     $sorts = [
655       'none' => $this->t('Unsorted'),
656     ];
657     // Check if we are allowed to sort by creation date.
658     $created_column = $this->getCreatedColumn();
659     if ($created_column) {
660       $sorts += [
661         $created_column . ':DESC' => $this->t('Newest first'),
662         $created_column . ':ASC' => $this->t('Oldest first'),
663       ];
664     }
665     if ($available_sorts = $this->getAvailableSorts()) {
666       $sorts += $available_sorts;
667     }
668
669     // If there is no sorts option available continue.
670     if (!empty($sorts)) {
671       $form['displays']['show']['sort'] = [
672         '#type' => 'select',
673         '#title' => $this->t('sorted by'),
674         '#options' => $sorts,
675         '#default_value' => isset($created_column) ? $created_column . ':DESC' : 'none',
676       ];
677     }
678   }
679
680   /**
681    * Instantiates a view object from form values.
682    *
683    * @return \Drupal\views_ui\ViewUI
684    *   The instantiated view UI object.
685    */
686   protected function instantiateView($form, FormStateInterface $form_state) {
687     // Build the basic view properties and create the view.
688     $values = [
689       'id' => $form_state->getValue('id'),
690       'label' => $form_state->getValue('label'),
691       'description' => $form_state->getValue('description'),
692       'base_table' => $this->base_table,
693       'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
694     ];
695
696     $view = View::create($values);
697
698     // Build all display options for this view.
699     $display_options = $this->buildDisplayOptions($form, $form_state);
700
701     // Allow the fully built options to be altered. This happens before adding
702     // the options to the view, so that once they are eventually added we will
703     // be able to get all the overrides correct.
704     $this->alterDisplayOptions($display_options, $form, $form_state);
705
706     $this->addDisplays($view, $display_options, $form, $form_state);
707
708     return new ViewUI($view);
709   }
710
711   /**
712    * Builds an array of display options for the view.
713    *
714    * @return array
715    *   An array whose keys are the names of each display and whose values are
716    *   arrays of options for that display.
717    */
718   protected function buildDisplayOptions($form, FormStateInterface $form_state) {
719     // Display: Master
720     $display_options['default'] = $this->defaultDisplayOptions();
721     $display_options['default'] += [
722       'filters' => [],
723       'sorts' => [],
724     ];
725     $display_options['default']['filters'] += $this->defaultDisplayFilters($form, $form_state);
726     $display_options['default']['sorts'] += $this->defaultDisplaySorts($form, $form_state);
727
728     // Display: Page
729     if (!$form_state->isValueEmpty(['page', 'create'])) {
730       $display_options['page'] = $this->pageDisplayOptions($form, $form_state);
731
732       // Display: Feed (attached to the page)
733       if (!$form_state->isValueEmpty(['page', 'feed'])) {
734         $display_options['feed'] = $this->pageFeedDisplayOptions($form, $form_state);
735       }
736     }
737
738     // Display: Block
739     if (!$form_state->isValueEmpty(['block', 'create'])) {
740       $display_options['block'] = $this->blockDisplayOptions($form, $form_state);
741     }
742
743     // Display: REST export.
744     if (!$form_state->isValueEmpty(['rest_export', 'create'])) {
745       $display_options['rest_export'] = $this->restExportDisplayOptions($form, $form_state);
746     }
747
748     return $display_options;
749   }
750
751   /**
752    * Alters the full array of display options before they are added to the view.
753    */
754   protected function alterDisplayOptions(&$display_options, $form, FormStateInterface $form_state) {
755     foreach ($display_options as $display_type => $options) {
756       // Allow style plugins to hook in and provide some settings.
757       $style_plugin = Views::pluginManager('style')->createInstance($options['style']['type']);
758       $style_plugin->wizardSubmit($form, $form_state, $this, $display_options, $display_type);
759     }
760   }
761
762   /**
763    * Adds the array of display options to the view, with appropriate overrides.
764    */
765   protected function addDisplays(View $view, $display_options, $form, FormStateInterface $form_state) {
766     // Initialize and store the view executable to get the display plugin
767     // instances.
768     $executable = $view->getExecutable();
769
770     // Display: Master
771     $default_display = $executable->newDisplay('default', 'Master', 'default');
772     foreach ($display_options['default'] as $option => $value) {
773       $default_display->setOption($option, $value);
774     }
775
776     // Display: Page
777     if (isset($display_options['page'])) {
778       $display = $executable->newDisplay('page', 'Page', 'page_1');
779       // The page display is usually the main one (from the user's point of
780       // view). Its options should therefore become the overall view defaults,
781       // so that new displays which are added later automatically inherit them.
782       $this->setDefaultOptions($display_options['page'], $display, $default_display);
783
784       // Display: Feed (attached to the page).
785       if (isset($display_options['feed'])) {
786         $display = $executable->newDisplay('feed', 'Feed', 'feed_1');
787         $this->setOverrideOptions($display_options['feed'], $display, $default_display);
788       }
789     }
790
791     // Display: Block.
792     if (isset($display_options['block'])) {
793       $display = $executable->newDisplay('block', 'Block', 'block_1');
794       // When there is no page, the block display options should become the
795       // overall view defaults.
796       if (!isset($display_options['page'])) {
797         $this->setDefaultOptions($display_options['block'], $display, $default_display);
798       }
799       else {
800         $this->setOverrideOptions($display_options['block'], $display, $default_display);
801       }
802     }
803
804     // Display: REST export.
805     if (isset($display_options['rest_export'])) {
806       $display = $executable->newDisplay('rest_export', 'REST export', 'rest_export_1');
807       // If there is no page or block, the REST export display options should
808       // become the overall view defaults.
809       if (!isset($display_options['page']) && !isset($display_options['block'])) {
810         $this->setDefaultOptions($display_options['rest_export'], $display, $default_display);
811       }
812       else {
813         $this->setOverrideOptions($display_options['rest_export'], $display, $default_display);
814       }
815     }
816
817     // Initialize displays and merge all plugin default values.
818     $executable->mergeDefaults();
819   }
820
821   /**
822    * Assembles the default display options for the view.
823    *
824    * Most wizards will need to override this method to provide some fields
825    * or a different row plugin.
826    *
827    * @return array
828    *   Returns an array of display options.
829    */
830   protected function defaultDisplayOptions() {
831     $display_options = [];
832     $display_options['access']['type'] = 'none';
833     $display_options['cache']['type'] = 'tag';
834     $display_options['query']['type'] = 'views_query';
835     $display_options['exposed_form']['type'] = 'basic';
836     $display_options['pager']['type'] = 'mini';
837     $display_options['style']['type'] = 'default';
838     $display_options['row']['type'] = 'fields';
839
840     // Add default options array to each plugin type.
841     foreach ($display_options as &$options) {
842       $options['options'] = [];
843     }
844
845     // Add a least one field so the view validates and the user has a preview.
846     // The base field can provide a default in its base settings; otherwise,
847     // choose the first field with a field handler.
848     $default_table = $this->base_table;
849     $data = Views::viewsData()->get($default_table);
850     if (isset($data['table']['base']['defaults']['field'])) {
851       $default_field = $data['table']['base']['defaults']['field'];
852       // If the table for the default field is different to the base table,
853       // load the view table data for this table.
854       if (isset($data['table']['base']['defaults']['table']) && $data['table']['base']['defaults']['table'] != $default_table) {
855         $default_table = $data['table']['base']['defaults']['table'];
856         $data = Views::viewsData()->get($default_table);
857       }
858     }
859     else {
860       foreach ($data as $default_field => $field_data) {
861         if (isset($field_data['field']['id'])) {
862           break;
863         }
864       }
865     }
866     // @todo Refactor the code to use ViewExecutable::addHandler. See
867     //   https://www.drupal.org/node/2383157.
868     $display_options['fields'][$default_field] = [
869       'table' => $default_table,
870       'field' => $default_field,
871       'id' => $default_field,
872       'entity_type' => isset($data[$default_field]['entity type']) ? $data[$default_field]['entity type'] : NULL,
873       'entity_field' => isset($data[$default_field]['entity field']) ? $data[$default_field]['entity field'] : NULL,
874       'plugin_id' => $data[$default_field]['field']['id'],
875     ];
876
877     return $display_options;
878   }
879
880   /**
881    * Retrieves all filter information used by the default display.
882    *
883    * Additional to the one provided by the plugin this method takes care about
884    * adding additional filters based on user input.
885    *
886    * @param array $form
887    *   The full wizard form array.
888    * @param \Drupal\Core\Form\FormStateInterface $form_state
889    *   The current state of the wizard form.
890    *
891    * @return array
892    *   An array of filter arrays keyed by ID. A sort array contains the options
893    *   accepted by a filter handler.
894    */
895   protected function defaultDisplayFilters($form, FormStateInterface $form_state) {
896     $filters = [];
897
898     // Add any filters provided by the plugin.
899     foreach ($this->getFilters() as $name => $info) {
900       $filters[$name] = $info;
901     }
902
903     // Add any filters specified by the user when filling out the wizard.
904     $filters = array_merge($filters, $this->defaultDisplayFiltersUser($form, $form_state));
905
906     return $filters;
907   }
908
909   /**
910    * Retrieves filter information based on user input for the default display.
911    *
912    * @param array $form
913    *   The full wizard form array.
914    * @param \Drupal\Core\Form\FormStateInterface $form_state
915    *   The current state of the wizard form.
916    *
917    * @return array
918    *   An array of filter arrays keyed by ID. A sort array contains the options
919    *   accepted by a filter handler.
920    */
921   protected function defaultDisplayFiltersUser(array $form, FormStateInterface $form_state) {
922     $filters = [];
923
924     if (($type = $form_state->getValue(['show', 'type'])) && $type != 'all') {
925       $bundle_key = $this->entityType->getKey('bundle');
926       // Figure out the table where $bundle_key lives. It may not be the same as
927       // the base table for the view; the taxonomy vocabulary machine_name, for
928       // example, is stored in taxonomy_vocabulary, not taxonomy_term_data.
929       module_load_include('inc', 'views_ui', 'admin');
930       $fields = Views::viewsDataHelper()->fetchFields($this->base_table, 'filter');
931       if (isset($fields[$this->base_table . '.' . $bundle_key])) {
932         $table = $this->base_table;
933       }
934       else {
935         foreach ($fields as $field_name => $value) {
936           if ($pos = strpos($field_name, '.' . $bundle_key)) {
937             $table = substr($field_name, 0, $pos);
938             break;
939           }
940         }
941       }
942       $table_data = Views::viewsData()->get($table);
943       // If the 'in' operator is being used, map the values to an array.
944       $handler = $table_data[$bundle_key]['filter']['id'];
945       $handler_definition = Views::pluginManager('filter')->getDefinition($handler);
946       if ($handler == 'in_operator' || is_subclass_of($handler_definition['class'], 'Drupal\\views\\Plugin\\views\\filter\\InOperator')) {
947         $value = [$type => $type];
948       }
949       // Otherwise, use just a single value.
950       else {
951         $value = $type;
952       }
953
954       $filters[$bundle_key] = [
955         'id' => $bundle_key,
956         'table' => $table,
957         'field' => $bundle_key,
958         'value' => $value,
959         'entity_type' => isset($table_data['table']['entity type']) ? $table_data['table']['entity type'] : NULL,
960         'entity_field' => isset($table_data[$bundle_key]['entity field']) ? $table_data[$bundle_key]['entity field'] : NULL,
961         'plugin_id' => $handler,
962       ];
963     }
964
965     return $filters;
966   }
967
968   /**
969    * Retrieves all sort information used by the default display.
970    *
971    * Additional to the one provided by the plugin this method takes care about
972    * adding additional sorts based on user input.
973    *
974    * @param array $form
975    *   The full wizard form array.
976    * @param \Drupal\Core\Form\FormStateInterface $form_state
977    *   The current state of the wizard form.
978    *
979    * @return array
980    *   An array of sort arrays keyed by ID. A sort array contains the options
981    *   accepted by a sort handler.
982    */
983   protected function defaultDisplaySorts($form, FormStateInterface $form_state) {
984     $sorts = [];
985
986     // Add any sorts provided by the plugin.
987     foreach ($this->getSorts() as $name => $info) {
988       $sorts[$name] = $info;
989     }
990
991     // Add any sorts specified by the user when filling out the wizard.
992     $sorts = array_merge($sorts, $this->defaultDisplaySortsUser($form, $form_state));
993
994     return $sorts;
995   }
996
997   /**
998    * Retrieves sort information based on user input for the default display.
999    *
1000    * @param array $form
1001    *   The full wizard form array.
1002    * @param \Drupal\Core\Form\FormStateInterface $form_state
1003    *   The current state of the wizard form.
1004    *
1005    * @return array
1006    *   An array of sort arrays keyed by ID. A sort array contains the options
1007    *   accepted by a sort handler.
1008    */
1009   protected function defaultDisplaySortsUser($form, FormStateInterface $form_state) {
1010     $sorts = [];
1011
1012     // Don't add a sort if there is no form value or the user set the sort to
1013     // 'none'.
1014     if (($sort_type = $form_state->getValue(['show', 'sort'])) && $sort_type != 'none') {
1015       list($column, $sort) = explode(':', $sort_type);
1016       // Column either be a column-name or the table-column-name.
1017       $column = explode('-', $column);
1018       if (count($column) > 1) {
1019         $table = $column[0];
1020         $column = $column[1];
1021       }
1022       else {
1023         $table = $this->base_table;
1024         $column = $column[0];
1025       }
1026
1027       // If the input is invalid, for example when the #default_value contains
1028       // created from node, but the wizard type is another base table, make
1029       // sure it is not added. This usually don't happen if you have js
1030       // enabled.
1031       $data = Views::viewsData()->get($table);
1032       if (isset($data[$column]['sort'])) {
1033         $sorts[$column] = [
1034           'id' => $column,
1035           'table' => $table,
1036           'field' => $column,
1037           'order' => $sort,
1038           'entity_type' => isset($data['table']['entity type']) ? $data['table']['entity type'] : NULL,
1039           'entity_field' => isset($data[$column]['entity field']) ? $data[$column]['entity field'] : NULL,
1040           'plugin_id' => $data[$column]['sort']['id'],
1041        ];
1042       }
1043     }
1044
1045     return $sorts;
1046   }
1047
1048   /**
1049    * Retrieves the page display options.
1050    *
1051    * @param array $form
1052    *   The full wizard form array.
1053    * @param \Drupal\Core\Form\FormStateInterface $form_state
1054    *   The current state of the wizard form.
1055    *
1056    * @return array
1057    *   Returns an array of display options.
1058    */
1059   protected function pageDisplayOptions(array $form, FormStateInterface $form_state) {
1060     $display_options = [];
1061     $page = $form_state->getValue('page');
1062     $display_options['title'] = $page['title'];
1063     $display_options['path'] = $page['path'];
1064     $display_options['style'] = ['type' => $page['style']['style_plugin']];
1065     // Not every style plugin supports row style plugins.
1066     // Make sure that the selected row plugin is a valid one.
1067     $options = $this->rowStyleOptions();
1068     $display_options['row'] = ['type' => (isset($page['style']['row_plugin']) && isset($options[$page['style']['row_plugin']])) ? $page['style']['row_plugin'] : 'fields'];
1069
1070     // If the specific 0 items per page, use no pager.
1071     if (empty($page['items_per_page'])) {
1072       $display_options['pager']['type'] = 'none';
1073     }
1074     // If the user checked the pager checkbox use a mini pager.
1075     elseif (!empty($page['pager'])) {
1076       $display_options['pager']['type'] = 'mini';
1077     }
1078     // If the user doesn't have checked the checkbox use the pager which just
1079     // displays a certain amount of items.
1080     else {
1081       $display_options['pager']['type'] = 'some';
1082     }
1083     $display_options['pager']['options']['items_per_page'] = $page['items_per_page'];
1084
1085     // Generate the menu links settings if the user checked the link checkbox.
1086     if (!empty($page['link'])) {
1087       $display_options['menu']['type'] = 'normal';
1088       $display_options['menu']['title'] = $page['link_properties']['title'];
1089       $display_options['menu']['menu_name'] = $page['link_properties']['menu_name'];
1090     }
1091     return $display_options;
1092   }
1093
1094   /**
1095    * Retrieves the block display options.
1096    *
1097    * @param array $form
1098    *   The full wizard form array.
1099    * @param \Drupal\Core\Form\FormStateInterface $form_state
1100    *   The current state of the wizard form.
1101    *
1102    * @return array
1103    *   Returns an array of display options.
1104    */
1105   protected function blockDisplayOptions(array $form, FormStateInterface $form_state) {
1106     $display_options = [];
1107     $block = $form_state->getValue('block');
1108     $display_options['title'] = $block['title'];
1109     $display_options['style'] = ['type' => $block['style']['style_plugin']];
1110     $options = $this->rowStyleOptions();
1111     $display_options['row'] = ['type' => (isset($block['style']['row_plugin']) && isset($options[$block['style']['row_plugin']])) ? $block['style']['row_plugin'] : 'fields'];
1112     $display_options['pager']['type'] = $block['pager'] ? 'full' : (empty($block['items_per_page']) ? 'none' : 'some');
1113     $display_options['pager']['options']['items_per_page'] = $block['items_per_page'];
1114     return $display_options;
1115   }
1116
1117   /**
1118    * Retrieves the REST export display options from the submitted form values.
1119    *
1120    * @param array $form
1121    *   The full wizard form array.
1122    * @param \Drupal\Core\Form\FormStateInterface $form_state
1123    *   The current state of the wizard form.
1124    *
1125    * @return array
1126    *   Returns an array of display options.
1127    */
1128   protected function restExportDisplayOptions(array $form, FormStateInterface $form_state) {
1129     $display_options = [];
1130     $display_options['path'] = $form_state->getValue(['rest_export', 'path']);
1131     $display_options['style'] = ['type' => 'serializer'];
1132
1133     return $display_options;
1134   }
1135
1136   /**
1137    * Retrieves the feed display options.
1138    *
1139    * @param array $form
1140    *   The full wizard form array.
1141    * @param \Drupal\Core\Form\FormStateInterface $form_state
1142    *   The current state of the wizard form.
1143    *
1144    * @return array
1145    *   Returns an array of display options.
1146    */
1147   protected function pageFeedDisplayOptions($form, FormStateInterface $form_state) {
1148     $display_options = [];
1149     $display_options['pager']['type'] = 'some';
1150     $display_options['style'] = ['type' => 'rss'];
1151     $display_options['row'] = ['type' => $form_state->getValue(['page', 'feed_properties', 'row_plugin'])];
1152     $display_options['path'] = $form_state->getValue(['page', 'feed_properties', 'path']);
1153     $display_options['title'] = $form_state->getValue(['page', 'title']);
1154     $display_options['displays'] = [
1155       'default' => 'default',
1156       'page_1' => 'page_1',
1157     ];
1158     return $display_options;
1159   }
1160
1161   /**
1162    * Sets options for a display and makes them the default options if possible.
1163    *
1164    * This function can be used to set options for a display when it is desired
1165    * that the options also become the defaults for the view whenever possible.
1166    * This should be done for the "primary" display created in the view wizard,
1167    * so that new displays which the user adds later will be similar to this
1168    * one.
1169    *
1170    * @param array $options
1171    *   An array whose keys are the name of each option and whose values are the
1172    *   desired values to set.
1173    * @param \Drupal\views\Plugin\views\display\DisplayPluginBase $display
1174    *   The display handler which the options will be applied to. The default
1175    *   display will actually be assigned the options (and this display will
1176    *   inherit them) when possible.
1177    * @param \Drupal\views\Plugin\views\display\DisplayPluginBase $default_display
1178    *   The default display handler, which will store the options when possible.
1179    */
1180   protected function setDefaultOptions($options, DisplayPluginBase $display, DisplayPluginBase $default_display) {
1181     foreach ($options as $option => $value) {
1182       // If the default display supports this option, set the value there.
1183       // Otherwise, set it on the provided display.
1184       $default_value = $default_display->getOption($option);
1185       if (isset($default_value)) {
1186         $default_display->setOption($option, $value);
1187       }
1188       else {
1189         $display->setOption($option, $value);
1190       }
1191     }
1192   }
1193
1194   /**
1195    * Sets options for a display, inheriting from the defaults when possible.
1196    *
1197    * This function can be used to set options for a display when it is desired
1198    * that the options inherit from the default display whenever possible. This
1199    * avoids setting too many options as overrides, which will be harder for the
1200    * user to modify later. For example, if $this->setDefaultOptions() was
1201    * previously called on a page display and then this function is called on a
1202    * block display, and if the user entered the same title for both displays in
1203    * the views wizard, then the view will wind up with the title stored as the
1204    * default (with the page and block both inheriting from it).
1205    *
1206    * @param array $options
1207    *   An array whose keys are the name of each option and whose values are the
1208    *   desired values to set.
1209    * @param \Drupal\views\Plugin\views\display\DisplayPluginBase $display
1210    *   The display handler which the options will be applied to. The default
1211    *   display will actually be assigned the options (and this display will
1212    *   inherit them) when possible.
1213    * @param \Drupal\views\Plugin\views\display\DisplayPluginBase $default_display
1214    *   The default display handler, which will store the options when possible.
1215    */
1216   protected function setOverrideOptions(array $options, DisplayPluginBase $display, DisplayPluginBase $default_display) {
1217     foreach ($options as $option => $value) {
1218       // Only override the default value if it is different from the value that
1219       // was provided.
1220       $default_value = $default_display->getOption($option);
1221       if (!isset($default_value)) {
1222         $display->setOption($option, $value);
1223       }
1224       elseif ($default_value !== $value) {
1225         $display->overrideOption($option, $value);
1226       }
1227     }
1228   }
1229
1230   /**
1231    * Retrieves a validated view for a form submission.
1232    *
1233    * @param array $form
1234    *   The full wizard form array.
1235    * @param \Drupal\Core\Form\FormStateInterface $form_state
1236    *   The current state of the wizard form.
1237    * @param bool $unset
1238    *   Should the view be removed from the list of validated views.
1239    *
1240    * @return \Drupal\views_ui\ViewUI
1241    *   The validated view object.
1242    */
1243   protected function retrieveValidatedView(array $form, FormStateInterface $form_state, $unset = TRUE) {
1244     // @todo Figure out why all this hashing is done. Wouldn't it be easier to
1245     //   store a single entry and that's it?
1246     $key = hash('sha256', serialize($form_state->getValues()));
1247     $view = (isset($this->validated_views[$key]) ? $this->validated_views[$key] : NULL);
1248     if ($unset) {
1249       unset($this->validated_views[$key]);
1250     }
1251     return $view;
1252   }
1253
1254   /**
1255    * Stores a validated view from a form submission.
1256    *
1257    * @param array $form
1258    *   The full wizard form array.
1259    * @param \Drupal\Core\Form\FormStateInterface $form_state
1260    *   The current state of the wizard form.
1261    * @param \Drupal\views_ui\ViewUI $view
1262    *   The validated view object.
1263    */
1264   protected function setValidatedView(array $form, FormStateInterface $form_state, ViewUI $view) {
1265     $key = hash('sha256', serialize($form_state->getValues()));
1266     $this->validated_views[$key] = $view;
1267   }
1268
1269   /**
1270    * Implements Drupal\views\Plugin\views\wizard\WizardInterface::validate().
1271    *
1272    * Instantiates the view from the form submission and validates its values.
1273    */
1274   public function validateView(array $form, FormStateInterface $form_state) {
1275     $view = $this->instantiateView($form, $form_state);
1276     $errors = $view->getExecutable()->validate();
1277
1278     if (empty($errors)) {
1279       $this->setValidatedView($form, $form_state, $view);
1280     }
1281
1282     return $errors;
1283   }
1284
1285   /**
1286    * {@inheritdoc}
1287    */
1288   public function createView(array $form, FormStateInterface $form_state) {
1289     $view = $this->retrieveValidatedView($form, $form_state);
1290     if (empty($view)) {
1291       throw new WizardException('Attempted to create a view with values that have not been validated.');
1292     }
1293     return $view;
1294   }
1295
1296 }
1297
1298 /**
1299  * @}
1300  */