3 namespace Drupal\views\Plugin\views\wizard;
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;
18 * @defgroup views_wizard_plugins Views wizard plugins
20 * Plugins for Views wizards.
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.
27 * @ingroup views_plugins
32 * Base class for Views wizard plugins.
34 * This is a very generic Views Wizard class that can be constructed for any
37 abstract class WizardPluginBase extends PluginBase implements WizardInterface {
39 use UrlGeneratorTrait;
42 * The base table connected with the wizard.
46 protected $base_table;
49 * The entity type connected with the wizard.
51 * There might be base tables connected with entity types, if not this would
56 protected $entityTypeId;
59 * Contains the information from entity_get_info of the $entity_type.
61 * @var \Drupal\Core\Entity\EntityTypeInterface
63 protected $entityType;
66 * An array of validated view objects, keyed by a hash.
70 protected $validated_views = [];
73 * The table column used for sorting by create date of this wizard.
77 protected $createdColumn;
80 * Views items configuration arrays for filters added by the wizard.
84 protected $filters = [];
87 * Views items configuration arrays for sorts added by the wizard.
91 protected $sorts = [];
94 * The available store criteria.
98 protected $availableSorts = [];
101 * Default values for filters.
103 * By default, filters are not exposed and added to the first non-reserved
108 protected $filter_defaults = [
110 'expose' => ['operator' => FALSE],
115 * The bundle info service.
117 * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
119 protected $bundleInfoService;
124 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
129 $container->get('entity_type.bundle.info')
134 * Constructs a WizardPluginBase object.
136 public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeBundleInfoInterface $bundle_info_service) {
137 parent::__construct($configuration, $plugin_id, $plugin_definition);
139 $this->bundleInfoService = $bundle_info_service;
140 $this->base_table = $this->definition['base_table'];
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;
152 * Gets the createdColumn property.
155 * The name of the column containing the created date.
157 public function getCreatedColumn() {
158 return $this->createdColumn;
162 * Gets the filters property.
166 public function getFilters() {
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');
175 'table' => $this->base_table,
176 'field' => $field_name,
177 'plugin_id' => 'boolean',
178 'entity_type' => $this->entityTypeId,
179 'entity_field' => $field_name,
184 $default = $this->filter_defaults;
186 foreach ($this->filters as $name => $info) {
187 $default['id'] = $name;
188 $filters[$name] = $info + $default;
195 * Gets the availableSorts property.
199 public function getAvailableSorts() {
200 return $this->availableSorts;
204 * Gets the sorts property.
208 public function getSorts() {
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]);
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);
224 $form['displays']['page'] = [
225 '#type' => 'fieldset',
226 '#title' => $this->t('Page settings'),
227 '#attributes' => ['class' => ['views-attachment', 'fieldset-no-legend']],
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',
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']],
245 ':input[name="page[create]"]' => ['checked' => TRUE],
248 '#prefix' => '<div><div id="edit-page-wrapper">',
249 '#suffix' => '</div></div>',
250 '#parents' => ['page'],
253 $form['displays']['page']['options']['title'] = [
254 '#title' => $this->t('Page title'),
255 '#type' => 'textfield',
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.
265 $form['displays']['page']['options']['style'] = [
266 '#type' => 'fieldset',
267 '#title' => $this->t('Page display settings'),
268 '#attributes' => ['class' => ['container-inline', 'fieldset-no-legend']],
271 // Create the dropdown for choosing the display format.
272 $form['displays']['page']['options']['style']['style_plugin'] = [
273 '#title' => $this->t('Display format'),
275 '#options' => $style_options,
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
281 views_ui_add_ajax_trigger($style_form, 'style_plugin', ['displays', 'page', 'options']);
283 $this->buildFormStyle($form, $form_state, 'page');
284 $form['displays']['page']['options']['items_per_page'] = [
285 '#title' => $this->t('Items to display'),
287 '#default_value' => 10,
290 $form['displays']['page']['options']['pager'] = [
291 '#title' => $this->t('Use a pager'),
292 '#type' => 'checkbox',
293 '#default_value' => TRUE,
295 $form['displays']['page']['options']['link'] = [
296 '#title' => $this->t('Create a menu link'),
297 '#type' => 'checkbox',
298 '#id' => 'edit-page-link',
300 $form['displays']['page']['options']['link_properties'] = [
301 '#type' => 'container',
304 ':input[name="page[link]"]' => ['checked' => TRUE],
307 '#prefix' => '<div id="edit-page-link-properties-wrapper">',
308 '#suffix' => '</div>',
310 if (\Drupal::moduleHandler()->moduleExists('menu_ui')) {
311 $menu_options = menu_ui_get_menus();
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);
320 $form['displays']['page']['options']['link_properties']['menu_name'] = [
321 '#title' => $this->t('Menu'),
323 '#options' => $menu_options,
325 $form['displays']['page']['options']['link_properties']['title'] = [
326 '#title' => $this->t('Link text'),
327 '#type' => 'textfield',
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',
336 $form['displays']['page']['options']['feed_properties'] = [
337 '#type' => 'container',
340 ':input[name="page[feed]"]' => ['checked' => TRUE],
343 '#prefix' => '<div id="edit-page-feed-properties-wrapper">',
344 '#suffix' => '</div>',
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.
353 // This will almost never be visible.
354 $form['displays']['page']['options']['feed_properties']['row_plugin'] = [
355 '#title' => $this->t('Feed row style'),
357 '#options' => $feed_row_options,
358 '#default_value' => key($feed_row_options),
359 '#access' => (count($feed_row_options) > 1),
362 ':input[name="page[feed]"]' => ['checked' => TRUE],
365 '#prefix' => '<div id="edit-page-feed-properties-row-plugin-wrapper">',
366 '#suffix' => '</div>',
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']],
378 $form['displays']['block']['create'] = [
379 '#title' => $this->t('Create a block'),
380 '#type' => 'checkbox',
381 '#attributes' => ['class' => ['strong']],
382 '#id' => 'edit-block-create',
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
388 $form['displays']['block']['options'] = [
389 '#type' => 'container',
390 '#attributes' => ['class' => ['options-set']],
393 ':input[name="block[create]"]' => ['checked' => TRUE],
396 '#prefix' => '<div id="edit-block-wrapper">',
397 '#suffix' => '</div>',
398 '#parents' => ['block'],
401 $form['displays']['block']['options']['title'] = [
402 '#title' => $this->t('Block title'),
403 '#type' => 'textfield',
406 $form['displays']['block']['options']['style'] = [
407 '#type' => 'fieldset',
408 '#title' => $this->t('Block display settings'),
409 '#attributes' => ['class' => ['container-inline', 'fieldset-no-legend']],
412 // Create the dropdown for choosing the display format.
413 $form['displays']['block']['options']['style']['style_plugin'] = [
414 '#title' => $this->t('Display format'),
416 '#options' => $style_options,
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']
422 views_ui_add_ajax_trigger($style_form, 'style_plugin', ['displays', 'block', 'options']);
424 $this->buildFormStyle($form, $form_state, 'block');
425 $form['displays']['block']['options']['items_per_page'] = [
426 '#title' => $this->t('Items per block'),
428 '#default_value' => 5,
431 $form['displays']['block']['options']['pager'] = [
432 '#title' => $this->t('Use a pager'),
433 '#type' => 'checkbox',
434 '#default_value' => FALSE,
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']],
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',
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']],
461 ':input[name="rest_export[create]"]' => ['checked' => TRUE],
464 '#prefix' => '<div id="edit-rest-export-wrapper">',
465 '#suffix' => '</div>',
466 '#parents' => ['rest_export'],
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.
482 * Gets the current value of a #select element, from within a form constructor function.
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.
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.
502 * @param \Drupal\Core\Form\FormStateInterface $form_state
503 * The current state of the form.
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.
516 * An array representing the current version of the #select element within
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.
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;
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)) {
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
555 if ($key_exists && in_array($submitted, array_keys($element['#options']))) {
560 // Fall back on returning the default value if nothing was returned above.
561 return $default_value;
565 * Adds the style options to the wizard 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').
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'] = [
582 '#title' => $this->t('of'),
583 '#options' => $options,
584 '#access' => count($options) > 1,
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']);
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'],
600 elseif ($style_plugin->usesFields()) {
601 $style_form['row_plugin'] = ['#markup' => '<span>' . $this->t('of fields') . '</span>'];
606 * Retrieves row style plugin names.
609 * Returns the plugin names available for the base table of the wizard.
611 protected function rowStyleOptions() {
612 // Get all available row plugins by default.
613 $options = Views::fetchPluginNames('row', 'normal', [$this->base_table]);
618 * Builds the form structure for selecting the view's filters.
620 * By default, this adds "of type" and "tagged with" filters (when they are
623 protected function buildFilters(&$form, FormStateInterface $form_state) {
624 module_load_include('inc', 'views_ui', 'admin');
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'];
634 $form['displays']['show']['type'] = [
636 '#title' => $this->t('of type'),
637 '#options' => $options,
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']);
649 * Builds the form structure for selecting the view's sort order.
651 * By default, this adds a "sorted by [date]" filter (when it is available).
653 protected function buildSorts(&$form, FormStateInterface $form_state) {
655 'none' => $this->t('Unsorted'),
657 // Check if we are allowed to sort by creation date.
658 $created_column = $this->getCreatedColumn();
659 if ($created_column) {
661 $created_column . ':DESC' => $this->t('Newest first'),
662 $created_column . ':ASC' => $this->t('Oldest first'),
665 if ($available_sorts = $this->getAvailableSorts()) {
666 $sorts += $available_sorts;
669 // If there is no sorts option available continue.
670 if (!empty($sorts)) {
671 $form['displays']['show']['sort'] = [
673 '#title' => $this->t('sorted by'),
674 '#options' => $sorts,
675 '#default_value' => isset($created_column) ? $created_column . ':DESC' : 'none',
681 * Instantiates a view object from form values.
683 * @return \Drupal\views_ui\ViewUI
684 * The instantiated view UI object.
686 protected function instantiateView($form, FormStateInterface $form_state) {
687 // Build the basic view properties and create the view.
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(),
696 $view = View::create($values);
698 // Build all display options for this view.
699 $display_options = $this->buildDisplayOptions($form, $form_state);
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);
706 $this->addDisplays($view, $display_options, $form, $form_state);
708 return new ViewUI($view);
712 * Builds an array of display options for the view.
715 * An array whose keys are the names of each display and whose values are
716 * arrays of options for that display.
718 protected function buildDisplayOptions($form, FormStateInterface $form_state) {
720 $display_options['default'] = $this->defaultDisplayOptions();
721 $display_options['default'] += [
725 $display_options['default']['filters'] += $this->defaultDisplayFilters($form, $form_state);
726 $display_options['default']['sorts'] += $this->defaultDisplaySorts($form, $form_state);
729 if (!$form_state->isValueEmpty(['page', 'create'])) {
730 $display_options['page'] = $this->pageDisplayOptions($form, $form_state);
732 // Display: Feed (attached to the page)
733 if (!$form_state->isValueEmpty(['page', 'feed'])) {
734 $display_options['feed'] = $this->pageFeedDisplayOptions($form, $form_state);
739 if (!$form_state->isValueEmpty(['block', 'create'])) {
740 $display_options['block'] = $this->blockDisplayOptions($form, $form_state);
743 // Display: REST export.
744 if (!$form_state->isValueEmpty(['rest_export', 'create'])) {
745 $display_options['rest_export'] = $this->restExportDisplayOptions($form, $form_state);
748 return $display_options;
752 * Alters the full array of display options before they are added to the view.
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);
763 * Adds the array of display options to the view, with appropriate overrides.
765 protected function addDisplays(View $view, $display_options, $form, FormStateInterface $form_state) {
766 // Initialize and store the view executable to get the display plugin
768 $executable = $view->getExecutable();
771 $default_display = $executable->newDisplay('default', 'Master', 'default');
772 foreach ($display_options['default'] as $option => $value) {
773 $default_display->setOption($option, $value);
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);
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);
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);
800 $this->setOverrideOptions($display_options['block'], $display, $default_display);
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);
813 $this->setOverrideOptions($display_options['rest_export'], $display, $default_display);
817 // Initialize displays and merge all plugin default values.
818 $executable->mergeDefaults();
822 * Assembles the default display options for the view.
824 * Most wizards will need to override this method to provide some fields
825 * or a different row plugin.
828 * Returns an array of display options.
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';
840 // Add default options array to each plugin type.
841 foreach ($display_options as &$options) {
842 $options['options'] = [];
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);
860 foreach ($data as $default_field => $field_data) {
861 if (isset($field_data['field']['id'])) {
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'],
877 return $display_options;
881 * Retrieves all filter information used by the default display.
883 * Additional to the one provided by the plugin this method takes care about
884 * adding additional filters based on user input.
887 * The full wizard form array.
888 * @param \Drupal\Core\Form\FormStateInterface $form_state
889 * The current state of the wizard form.
892 * An array of filter arrays keyed by ID. A sort array contains the options
893 * accepted by a filter handler.
895 protected function defaultDisplayFilters($form, FormStateInterface $form_state) {
898 // Add any filters provided by the plugin.
899 foreach ($this->getFilters() as $name => $info) {
900 $filters[$name] = $info;
903 // Add any filters specified by the user when filling out the wizard.
904 $filters = array_merge($filters, $this->defaultDisplayFiltersUser($form, $form_state));
910 * Retrieves filter information based on user input for the default display.
913 * The full wizard form array.
914 * @param \Drupal\Core\Form\FormStateInterface $form_state
915 * The current state of the wizard form.
918 * An array of filter arrays keyed by ID. A sort array contains the options
919 * accepted by a filter handler.
921 protected function defaultDisplayFiltersUser(array $form, FormStateInterface $form_state) {
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;
935 foreach ($fields as $field_name => $value) {
936 if ($pos = strpos($field_name, '.' . $bundle_key)) {
937 $table = substr($field_name, 0, $pos);
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];
949 // Otherwise, use just a single value.
954 $filters[$bundle_key] = [
957 'field' => $bundle_key,
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,
969 * Retrieves all sort information used by the default display.
971 * Additional to the one provided by the plugin this method takes care about
972 * adding additional sorts based on user input.
975 * The full wizard form array.
976 * @param \Drupal\Core\Form\FormStateInterface $form_state
977 * The current state of the wizard form.
980 * An array of sort arrays keyed by ID. A sort array contains the options
981 * accepted by a sort handler.
983 protected function defaultDisplaySorts($form, FormStateInterface $form_state) {
986 // Add any sorts provided by the plugin.
987 foreach ($this->getSorts() as $name => $info) {
988 $sorts[$name] = $info;
991 // Add any sorts specified by the user when filling out the wizard.
992 $sorts = array_merge($sorts, $this->defaultDisplaySortsUser($form, $form_state));
998 * Retrieves sort information based on user input for the default display.
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.
1006 * An array of sort arrays keyed by ID. A sort array contains the options
1007 * accepted by a sort handler.
1009 protected function defaultDisplaySortsUser($form, FormStateInterface $form_state) {
1012 // Don't add a sort if there is no form value or the user set the sort to
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];
1023 $table = $this->base_table;
1024 $column = $column[0];
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
1031 $data = Views::viewsData()->get($table);
1032 if (isset($data[$column]['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'],
1049 * Retrieves the page display options.
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.
1057 * Returns an array of display options.
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'];
1070 // If the specific 0 items per page, use no pager.
1071 if (empty($page['items_per_page'])) {
1072 $display_options['pager']['type'] = 'none';
1074 // If the user checked the pager checkbox use a mini pager.
1075 elseif (!empty($page['pager'])) {
1076 $display_options['pager']['type'] = 'mini';
1078 // If the user doesn't have checked the checkbox use the pager which just
1079 // displays a certain amount of items.
1081 $display_options['pager']['type'] = 'some';
1083 $display_options['pager']['options']['items_per_page'] = $page['items_per_page'];
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'];
1091 return $display_options;
1095 * Retrieves the block display options.
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.
1103 * Returns an array of display options.
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;
1118 * Retrieves the REST export display options from the submitted form values.
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.
1126 * Returns an array of display options.
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'];
1133 return $display_options;
1137 * Retrieves the feed display options.
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.
1145 * Returns an array of display options.
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',
1158 return $display_options;
1162 * Sets options for a display and makes them the default options if possible.
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
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.
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);
1189 $display->setOption($option, $value);
1195 * Sets options for a display, inheriting from the defaults when possible.
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).
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.
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
1220 $default_value = $default_display->getOption($option);
1221 if (!isset($default_value)) {
1222 $display->setOption($option, $value);
1224 elseif ($default_value !== $value) {
1225 $display->overrideOption($option, $value);
1231 * Retrieves a validated view for a form submission.
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.
1240 * @return \Drupal\views_ui\ViewUI
1241 * The validated view object.
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);
1249 unset($this->validated_views[$key]);
1255 * Stores a validated view from a form submission.
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.
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;
1270 * Implements Drupal\views\Plugin\views\wizard\WizardInterface::validate().
1272 * Instantiates the view from the form submission and validates its values.
1274 public function validateView(array $form, FormStateInterface $form_state) {
1275 $view = $this->instantiateView($form, $form_state);
1276 $errors = $view->getExecutable()->validate();
1278 if (empty($errors)) {
1279 $this->setValidatedView($form, $form_state, $view);
1288 public function createView(array $form, FormStateInterface $form_state) {
1289 $view = $this->retrieveValidatedView($form, $form_state);
1291 throw new WizardException('Attempted to create a view with values that have not been validated.');