ViewEditForm.php 44.3 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains Drupal\views_ui\ViewEditForm.
6 7 8 9
 */

namespace Drupal\views_ui;

10
use Drupal\Component\Utility\UrlHelper;
11
use Drupal\Component\Utility\Xss;
12 13 14
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
15
use Drupal\Core\Datetime\DateFormatter;
16
use Drupal\Component\Utility\NestedArray;
17
use Drupal\Component\Utility\String;
18
use Drupal\Core\Form\FormStateInterface;
19
use Drupal\Core\Render\Element;
20
use Drupal\Core\Url;
21
use Drupal\user\TempStoreFactory;
22
use Drupal\views\Views;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\RequestStack;
25
use Symfony\Component\DependencyInjection\ContainerInterface;
26 27 28 29

/**
 * Form controller for the Views edit form.
 */
30
class ViewEditForm extends ViewFormBase {
31 32 33 34 35 36 37 38 39 40 41

  /**
   * The views temp store.
   *
   * @var \Drupal\user\TempStore
   */
  protected $tempStore;

  /**
   * The request object.
   *
42
   * @var \Symfony\Component\HttpFoundation\RequestStack
43
   */
44
  protected $requestStack;
45

46 47 48
  /**
   * The date formatter service.
   *
49
   * @var \Drupal\Core\Datetime\DateFormatter
50 51 52
   */
  protected $dateFormatter;

53
  /**
54
   * Constructs a new ViewEditForm object.
55 56 57
   *
   * @param \Drupal\user\TempStoreFactory $temp_store_factory
   *   The factory for the temp store object.
58 59
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack object.
60
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
61
   *   The date Formatter service.
62
   */
63
  public function __construct(TempStoreFactory $temp_store_factory, RequestStack $requestStack, DateFormatter $date_formatter) {
64
    $this->tempStore = $temp_store_factory->get('views');
65
    $this->requestStack = $requestStack;
66
    $this->dateFormatter = $date_formatter;
67 68 69 70 71
  }

  /**
   * {@inheritdoc}
   */
72
  public static function create(ContainerInterface $container) {
73 74
    return new static(
      $container->get('user.tempstore'),
75
      $container->get('request_stack'),
76
      $container->get('date.formatter')
77 78
    );
  }
79 80

  /**
81
   * {@inheritdoc}
82
   */
83
  public function form(array $form, FormStateInterface $form_state) {
84
    $view = $this->entity;
85
    $display_id = $this->displayID;
86
    // Do not allow the form to be cached, because $form_state->get('view') can become
87 88 89
    // stale between page requests.
    // See views_ui_ajax_get_form() for how this affects #ajax.
    // @todo To remove this and allow the form to be cacheable:
90 91
    //   - Change $form_state->get('view') to $form_state->getTemporary()['view'].
    //   - Add a #process function to initialize $form_state->getTemporary()['view']
92
    //     on cached form submissions.
93
    //   - Use \Drupal\Core\Form\FormStateInterface::loadInclude().
94
    $form_state->disableCache();
95 96

    if ($display_id) {
97
      if (!$view->getExecutable()->setDisplay($display_id)) {
98
        $form['#markup'] = $this->t('Invalid display id @display', array('@display' => $display_id));
99 100 101 102 103 104
        return $form;
      }
    }

    $form['#tree'] = TRUE;

105 106 107 108
    $form['#attached']['library'][] = 'core/jquery.ui.tabs';
    $form['#attached']['library'][] = 'core/jquery.ui.dialog';
    $form['#attached']['library'][] = 'core/drupal.states';
    $form['#attached']['library'][] = 'core/drupal.tabledrag';
109

110
    if (!\Drupal::config('views.settings')->get('no_javascript')) {
111
      $form['#attached']['library'][] = 'views_ui/views_ui.admin';
112 113
    }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    $form['#attached']['css'] = static::getAdminCSS();

    $form['#attached']['js'][] = array(
      'data' => array('views' => array('ajax' => array(
        'id' => '#views-ajax-body',
        'title' => '#views-ajax-title',
        'popup' => '#views-ajax-popup',
        'defaultForm' => $view->getDefaultAJAXMessage(),
      ))),
      'type' => 'setting',
    );

    $form += array(
      '#prefix' => '',
      '#suffix' => '',
    );
130 131 132

    $view_status = $view->status() ? 'enabled' : 'disabled';
    $form['#prefix'] .= '<div class="views-edit-view views-admin ' . $view_status . ' clearfix">';
133 134 135 136
    $form['#suffix'] = '</div>' . $form['#suffix'];

    $form['#attributes']['class'] = array('form-edit');

137
    if ($view->isLocked()) {
138 139 140 141 142 143
      $username = array(
        '#theme' => 'username',
        '#account' => user_load($view->lock->owner),
      );
      $lock_message_substitutions = array(
        '!user' => drupal_render($username),
144
        '!age' => $this->dateFormatter->formatInterval(REQUEST_TIME - $view->lock->updated),
145
        '!break' => $view->url('break-lock-form'),
146
      );
147 148
      $form['locked'] = array(
        '#type' => 'container',
149
        '#attributes' => array('class' => array('view-locked', 'messages', 'messages--warning')),
150
        '#children' => $this->t('This view is being edited by user !user, and is therefore locked from editing by others. This lock is !age old. Click here to <a href="!break">break this lock</a>.', $lock_message_substitutions),
151 152 153 154 155 156
        '#weight' => -10,
      );
    }
    else {
      $form['changed'] = array(
        '#type' => 'container',
157
        '#attributes' => array('class' => array('view-changed', 'messages', 'messages--warning')),
158
        '#children' => $this->t('You have unsaved changes.'),
159 160 161 162 163 164 165 166
        '#weight' => -10,
      );
      if (empty($view->changed)) {
        $form['changed']['#attributes']['class'][] = 'js-hide';
      }
    }

    $form['displays'] = array(
167
      '#prefix' => '<h1 class="unit-title clearfix">' . $this->t('Displays') . '</h1>',
168 169 170 171 172 173 174 175 176 177 178 179 180
      '#type' => 'container',
      '#attributes' => array(
        'class' => array(
          'views-displays',
        ),
      ),
    );


    $form['displays']['top'] = $this->renderDisplayTop($view);

    // The rest requires a display to be selected.
    if ($display_id) {
181
      $form_state->set('display_id', $display_id);
182 183 184 185 186 187 188 189

      // The part of the page where editing will take place.
      $form['displays']['settings'] = array(
        '#type' => 'container',
        '#id' => 'edit-display-settings',
      );

      // Add a text that the display is disabled.
190 191
      if ($view->getExecutable()->displayHandlers->has($display_id)) {
        if (!$view->getExecutable()->displayHandlers->get($display_id)->isEnabled()) {
192
          $form['displays']['settings']['disabled']['#markup'] = $this->t('This display is disabled.');
193 194 195 196 197 198 199 200 201 202 203 204 205 206
        }
      }

      // Add the edit display content
      $tab_content = $this->getDisplayTab($view);
      $tab_content['#theme_wrappers'] = array('container');
      $tab_content['#attributes'] = array('class' => array('views-display-tab'));
      $tab_content['#id'] = 'views-tab-' . $display_id;
      // Mark deleted displays as such.
      $display = $view->get('display');
      if (!empty($display[$display_id]['deleted'])) {
        $tab_content['#attributes']['class'][] = 'views-display-deleted';
      }
      // Mark disabled displays as such.
207

208
      if ($view->getExecutable()->displayHandlers->has($display_id) && !$view->getExecutable()->displayHandlers->get($display_id)->isEnabled()) {
209 210 211 212 213 214 215 216 217 218 219 220 221
        $tab_content['#attributes']['class'][] = 'views-display-disabled';
      }
      $form['displays']['settings']['settings_content'] = array(
        '#type' => 'container',
        'tab_content' => $tab_content,
      );

      // The content of the popup dialog.
      $form['ajax-area'] = array(
        '#type' => 'container',
        '#id' => 'views-ajax-popup',
      );
      $form['ajax-area']['ajax-title'] = array(
222
        '#markup' => '<div id="views-ajax-title"></div>',
223 224 225 226 227 228 229 230 231 232 233 234
      );
      $form['ajax-area']['ajax-body'] = array(
        '#type' => 'container',
        '#id' => 'views-ajax-body',
        '#children' => $view->getDefaultAJAXMessage(),
      );
    }

    return $form;
  }

  /**
235
   * {@inheritdoc}
236
   */
237
  protected function actions(array $form, FormStateInterface $form_state) {
238 239 240 241
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);

    $actions['cancel'] = array(
242
      '#type' => 'submit',
243
      '#value' => $this->t('Cancel'),
244
      '#submit' => array('::cancel'),
245
    );
246 247 248 249
    if ($this->entity->isLocked()) {
      $actions['submit']['#access'] = FALSE;
      $actions['cancel']['#access'] = FALSE;
    }
250 251 252 253
    return $actions;
  }

  /**
254
   * {@inheritdoc}
255
   */
256
  public function validate(array $form, FormStateInterface $form_state) {
257 258
    parent::validate($form, $form_state);

259
    $view = $this->entity;
260
    if ($view->isLocked()) {
261
      $form_state->setErrorByName('', $this->t('Changes cannot be made to a locked view.'));
262
    }
263
    foreach ($view->getExecutable()->validate() as $display_errors) {
264
      foreach ($display_errors as $error) {
265
        $form_state->setErrorByName('', $error);
266 267 268 269 270
      }
    }
  }

  /**
271
   * {@inheritdoc}
272
   */
273
  public function save(array $form, FormStateInterface $form_state) {
274
    $view = $this->entity;
275 276
    $executable = $view->getExecutable();

277 278 279 280
    // Go through and remove displayed scheduled for removal.
    $displays = $view->get('display');
    foreach ($displays as $id => $display) {
      if (!empty($display['deleted'])) {
281
        $executable->displayHandlers->remove($id);
282 283 284
        unset($displays[$id]);
      }
    }
285

286
    // Rename display ids if needed.
287
    foreach ($executable->displayHandlers as $id => $display) {
288 289
      if (!empty($display->display['new_id'])) {
        $new_id = $display->display['new_id'];
290 291 292
        $display->display['id'] = $new_id;
        unset($display->display['new_id']);
        $executable->displayHandlers->set($new_id, $display);
293 294 295

        $displays[$new_id] = $displays[$id];
        unset($displays[$id]);
296

297
        // Redirect the user to the renamed display to be sure that the page itself exists and doesn't throw errors.
298
        $form_state->setRedirect('entity.view.edit_display_form', array(
299 300 301
          'view' => $view->id(),
          'display_id' => $new_id,
        ));
302 303 304 305 306
      }
    }
    $view->set('display', $displays);

    // @todo: Revisit this when http://drupal.org/node/1668866 is in.
307
    $query = $this->requestStack->getCurrentRequest()->query;
308
    $destination = $query->get('destination');
309

310 311
    if (!empty($destination)) {
      // Find out the first display which has a changed path and redirect to this url.
312
      $old_view = Views::getView($view->id());
313 314 315 316 317 318 319 320
      $old_view->initDisplay();
      foreach ($old_view->displayHandlers as $id => $display) {
        // Only check for displays with a path.
        $old_path = $display->getOption('path');
        if (empty($old_path)) {
          continue;
        }

321 322
        if (($display->getPluginId() == 'page') && ($old_path == $destination) && ($old_path != $view->getExecutable()->displayHandlers->get($id)->getOption('path'))) {
          $destination = $view->getExecutable()->displayHandlers->get($id)->getOption('path');
323 324 325
          $query->remove('destination');
        }
      }
326
      $form_state->setRedirectUrl(Url::fromUri("base://$destination"));
327 328 329
    }

    $view->save();
330

331
    drupal_set_message($this->t('The view %name has been saved.', array('%name' => $view->label())));
332 333

    // Remove this view from cache so we can edit it properly.
334
    $this->tempStore->delete($view->id());
335 336 337 338 339 340 341
  }

  /**
   * Form submission handler for the 'cancel' action.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
342 343
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
344
   */
345
  public function cancel(array $form, FormStateInterface $form_state) {
346
    // Remove this view from cache so edits will be lost.
347
    $view = $this->entity;
348
    $this->tempStore->delete($view->id());
349
    $form_state->setRedirect('views_ui.list');
350 351 352 353 354 355 356
  }

  /**
   * Returns a renderable array representing the edit page for one display.
   */
  public function getDisplayTab($view) {
    $build = array();
357
    $display_id = $this->displayID;
358
    $display = $view->getExecutable()->displayHandlers->get($display_id);
359 360 361 362
    // If the plugin doesn't exist, display an error message instead of an edit
    // page.
    if (empty($display)) {
      // @TODO: Improved UX for the case where a plugin is missing.
363
      $build['#markup'] = $this->t("Error: Display @display refers to a plugin named '@plugin', but that plugin is not available.", array('@display' => $display->display['id'], '@plugin' => $display->display['display_plugin']));
364 365 366 367 368 369 370
    }
    // Build the content of the edit page.
    else {
      $build['details'] = $this->getDisplayDetails($view, $display->display);
    }
    // In AJAX context, ViewUI::rebuildCurrentTab() returns this outside of form
    // context, so hook_form_views_ui_edit_form_alter() is insufficient.
371
    \Drupal::moduleHandler()->alter('views_ui_display_tab', $build, $view, $display_id);
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    return $build;
  }

  /**
   * Helper function to get the display details section of the edit UI.
   *
   * @param $display
   *
   * @return array
   *   A renderable page build array.
   */
  public function getDisplayDetails($view, $display) {
    $display_title = $this->getDisplayLabel($view, $display['id'], FALSE);
    $build = array(
      '#theme_wrappers' => array('container'),
      '#attributes' => array('id' => 'edit-display-settings-details'),
    );

    $is_display_deleted = !empty($display['deleted']);
391
    // The master display cannot be duplicated.
392 393
    $is_default = $display['id'] == 'default';
    // @todo: Figure out why getOption doesn't work here.
394
    $is_enabled = $view->getExecutable()->displayHandlers->get($display['id'])->isEnabled();
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

    if ($display['id'] != 'default') {
      $build['top']['#theme_wrappers'] = array('container');
      $build['top']['#attributes']['id'] = 'edit-display-settings-top';
      $build['top']['#attributes']['class'] = array('views-ui-display-tab-actions', 'views-ui-display-tab-bucket', 'clearfix');

      // The Delete, Duplicate and Undo Delete buttons.
      $build['top']['actions'] = array(
        '#theme_wrappers' => array('dropbutton_wrapper'),
      );

      // Because some of the 'links' are actually submit buttons, we have to
      // manually wrap each item in <li> and the whole list in <ul>.
      $build['top']['actions']['prefix']['#markup'] = '<ul class="dropbutton">';

      if (!$is_display_deleted) {
        if (!$is_enabled) {
          $build['top']['actions']['enable'] = array(
            '#type' => 'submit',
414
            '#value' => $this->t('Enable !display_title', array('!display_title' => $display_title)),
415
            '#limit_validation_errors' => array(),
416
            '#submit' => array('::submitDisplayEnable', '::submitDelayDestination'),
417 418 419 420
            '#prefix' => '<li class="enable">',
            "#suffix" => '</li>',
          );
        }
421 422
        // Add a link to view the page unless the view is disabled or has no
        // path.
423 424
        elseif ($view->status() && $view->getExecutable()->displayHandlers->get($display['id'])->hasPath()) {
          $path = $view->getExecutable()->displayHandlers->get($display['id'])->getPath();
425
          if ($path && (strpos($path, '%') === FALSE)) {
426 427
            $build['top']['actions']['path'] = array(
              '#type' => 'link',
428
              '#title' => $this->t('View !display_title', array('!display_title' => $display_title)),
429
              '#options' => array('alt' => array($this->t("Go to the real page for this display"))),
430 431 432 433 434 435 436 437 438
              '#href' => $path,
              '#prefix' => '<li class="view">',
              "#suffix" => '</li>',
            );
          }
        }
        if (!$is_default) {
          $build['top']['actions']['duplicate'] = array(
            '#type' => 'submit',
439
            '#value' => $this->t('Duplicate !display_title', array('!display_title' => $display_title)),
440
            '#limit_validation_errors' => array(),
441
            '#submit' => array('::submitDisplayDuplicate', '::submitDelayDestination'),
442 443 444 445 446 447 448
            '#prefix' => '<li class="duplicate">',
            "#suffix" => '</li>',
          );
        }
        // Always allow a display to be deleted.
        $build['top']['actions']['delete'] = array(
          '#type' => 'submit',
449
          '#value' => $this->t('Delete !display_title', array('!display_title' => $display_title)),
450
          '#limit_validation_errors' => array(),
451
          '#submit' => array('::submitDisplayDelete', '::submitDelayDestination'),
452 453 454
          '#prefix' => '<li class="delete">',
          "#suffix" => '</li>',
        );
455

456
        foreach (Views::fetchPluginNames('display', NULL, array($view->get('storage')->get('base_table'))) as $type => $label) {
457 458 459 460
          if ($type == $display['display_plugin']) {
            continue;
          }

461
          $build['top']['actions']['duplicate_as'][$type] = array(
462
            '#type' => 'submit',
463
            '#value' => $this->t('Duplicate as !type', array('!type' => $label)),
464
            '#limit_validation_errors' => array(),
465
            '#submit' => array('::submitDuplicateDisplayAsType', '::submitDelayDestination'),
466 467 468 469
            '#prefix' => '<li class="duplicate">',
            '#suffix' => '</li>',
          );
        }
470 471 472 473
      }
      else {
        $build['top']['actions']['undo_delete'] = array(
          '#type' => 'submit',
474
          '#value' => $this->t('Undo delete of !display_title', array('!display_title' => $display_title)),
475
          '#limit_validation_errors' => array(),
476
          '#submit' => array('::submitDisplayUndoDelete', '::submitDelayDestination'),
477 478 479 480
          '#prefix' => '<li class="undo-delete">',
          "#suffix" => '</li>',
        );
      }
481 482 483
      if ($is_enabled) {
        $build['top']['actions']['disable'] = array(
          '#type' => 'submit',
484
          '#value' => $this->t('Disable !display_title', array('!display_title' => $display_title)),
485
          '#limit_validation_errors' => array(),
486
          '#submit' => array('::submitDisplayDisable', '::submitDelayDestination'),
487 488 489 490
          '#prefix' => '<li class="disable">',
          "#suffix" => '</li>',
        );
      }
491 492 493 494 495
      $build['top']['actions']['suffix']['#markup'] = '</ul>';

      // The area above the three columns.
      $build['top']['display_title'] = array(
        '#theme' => 'views_ui_display_tab_setting',
496
        '#description' => $this->t('Display name'),
497
        '#link' => $view->getExecutable()->displayHandlers->get($display['id'])->optionLink(String::checkPlain($display_title), 'display_title'),
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      );
    }

    $build['columns'] = array();
    $build['columns']['#theme_wrappers'] = array('container');
    $build['columns']['#attributes'] = array('id' => 'edit-display-settings-main', 'class' => array('clearfix', 'views-display-columns'));

    $build['columns']['first']['#theme_wrappers'] = array('container');
    $build['columns']['first']['#attributes'] = array('class' => array('views-display-column', 'first'));

    $build['columns']['second']['#theme_wrappers'] = array('container');
    $build['columns']['second']['#attributes'] = array('class' => array('views-display-column', 'second'));

    $build['columns']['second']['settings'] = array();
    $build['columns']['second']['header'] = array();
    $build['columns']['second']['footer'] = array();
514
    $build['columns']['second']['empty'] = array();
515 516
    $build['columns']['second']['pager'] = array();

517
    // The third column buckets are wrapped in details.
518
    $build['columns']['third'] = array(
519
      '#type' => 'details',
520
      '#title' => $this->t('Advanced'),
521
      '#theme_wrappers' => array('details'),
522 523 524 525 526 527 528
      '#attributes' => array(
        'class' => array(
          'views-display-column',
          'third',
        ),
      ),
    );
529
    // Collapse the details by default.
530
    $build['columns']['third']['#open'] = \Drupal::config('views.settings')->get('ui.show.advanced_column');
531 532 533 534 535 536 537

    // Each option (e.g. title, access, display as grid/table/list) fits into one
    // of several "buckets," or boxes (Format, Fields, Sort, and so on).
    $buckets = array();

    // Fetch options from the display plugin, with a list of buckets they go into.
    $options = array();
538
    $view->getExecutable()->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569

    // Place each option into its bucket.
    foreach ($options as $id => $option) {
      // Each option self-identifies as belonging in a particular bucket.
      $buckets[$option['category']]['build'][$id] = $this->buildOptionForm($view, $id, $option, $display);
    }

    // Place each bucket into the proper column.
    foreach ($buckets as $id => $bucket) {
      // Let buckets identify themselves as belonging in a column.
      if (isset($bucket['column']) && isset($build['columns'][$bucket['column']])) {
        $column = $bucket['column'];
      }
      // If a bucket doesn't pick one of our predefined columns to belong to, put
      // it in the last one.
      else {
        $column = 'third';
      }
      if (isset($bucket['build']) && is_array($bucket['build'])) {
        $build['columns'][$column][$id] = $bucket['build'];
        $build['columns'][$column][$id]['#theme_wrappers'][] = 'views_ui_display_tab_bucket';
        $build['columns'][$column][$id]['#title'] = !empty($bucket['title']) ? $bucket['title'] : '';
        $build['columns'][$column][$id]['#name'] = !empty($bucket['title']) ? $bucket['title'] : $id;
      }
    }

    $build['columns']['first']['fields'] = $this->getFormBucket($view, 'field', $display);
    $build['columns']['first']['filters'] = $this->getFormBucket($view, 'filter', $display);
    $build['columns']['first']['sorts'] = $this->getFormBucket($view, 'sort', $display);
    $build['columns']['second']['header'] = $this->getFormBucket($view, 'header', $display);
    $build['columns']['second']['footer'] = $this->getFormBucket($view, 'footer', $display);
570
    $build['columns']['second']['empty'] = $this->getFormBucket($view, 'empty', $display);
571 572 573 574 575 576 577 578 579
    $build['columns']['third']['arguments'] = $this->getFormBucket($view, 'argument', $display);
    $build['columns']['third']['relationships'] = $this->getFormBucket($view, 'relationship', $display);

    return $build;
  }

  /**
   * Submit handler to add a restore a removed display to a view.
   */
580
  public function submitDisplayUndoDelete($form, FormStateInterface $form_state) {
581
    $view = $this->entity;
582
    // Create the new display
583
    $id = $form_state->get('display_id');
584 585 586 587 588
    $displays = $view->get('display');
    $displays[$id]['deleted'] = FALSE;
    $view->set('display', $displays);

    // Store in cache
589
    $view->cacheSet();
590 591

    // Redirect to the top-level edit page.
592
    $form_state->setRedirect('entity.view.edit_display_form', array(
593 594 595
      'view' => $view->id(),
      'display_id' => $id,
    ));
596 597 598 599 600
  }

  /**
   * Submit handler to enable a disabled display.
   */
601
  public function submitDisplayEnable($form, FormStateInterface $form_state) {
602
    $view = $this->entity;
603
    $id = $form_state->get('display_id');
604
    // setOption doesn't work because this would might affect upper displays
605
    $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', TRUE);
606 607

    // Store in cache
608
    $view->cacheSet();
609 610

    // Redirect to the top-level edit page.
611
    $form_state->setRedirect('entity.view.edit_display_form', array(
612 613 614
      'view' => $view->id(),
      'display_id' => $id,
    ));
615 616 617 618 619
  }

  /**
   * Submit handler to disable display.
   */
620
  public function submitDisplayDisable($form, FormStateInterface $form_state) {
621
    $view = $this->entity;
622
    $id = $form_state->get('display_id');
623
    $view->getExecutable()->displayHandlers->get($id)->setOption('enabled', FALSE);
624 625

    // Store in cache
626
    $view->cacheSet();
627 628

    // Redirect to the top-level edit page.
629
    $form_state->setRedirect('entity.view.edit_display_form', array(
630 631 632
      'view' => $view->id(),
      'display_id' => $id,
    ));
633 634 635 636 637
  }

  /**
   * Submit handler to delete a display from a view.
   */
638
  public function submitDisplayDelete($form, FormStateInterface $form_state) {
639
    $view = $this->entity;
640
    $display_id = $form_state->get('display_id');
641 642 643 644 645

    // Mark the display for deletion.
    $displays = $view->get('display');
    $displays[$display_id]['deleted'] = TRUE;
    $view->set('display', $displays);
646
    $view->cacheSet();
647 648 649

    // Redirect to the top-level edit page. The first remaining display will
    // become the active display.
650
    $form_state->setRedirectUrl($view->urlInfo('edit-form'));
651 652 653 654
  }

  /**
   * Regenerate the current tab for AJAX updates.
655 656 657 658 659 660 661
   *
   * @param \Drupal\views_ui\ViewUI $view
   *   The view to regenerate its tab.
   * @param \Drupal\Core\Ajax\AjaxResponse $response
   *   The response object to add new commands to.
   * @param string $display_id
   *   The display ID of the tab to regenerate.
662
   */
663
  public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
664
    $this->displayID = $display_id;
665
    if (!$view->getExecutable()->setDisplay('default')) {
666 667 668 669
      return;
    }

    // Regenerate the main display area.
670
    $build = $this->getDisplayTab($view);
671
    static::addMicroweights($build);
672
    $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, drupal_render($build)));
673 674 675 676

    // Regenerate the top area so changes to display names and order will appear.
    $build = $this->renderDisplayTop($view);
    static::addMicroweights($build);
677
    $response->addCommand(new ReplaceCommand('#views-display-top', drupal_render($build)));
678 679 680 681 682 683
  }

  /**
   * Render the top of the display so it can be updated during ajax operations.
   */
  public function renderDisplayTop(ViewUI $view) {
684
    $display_id = $this->displayID;
685
    $element['#theme_wrappers'][] = 'views_ui_container';
686 687 688 689 690 691 692 693 694 695 696
    $element['#attributes']['class'] = array('views-display-top', 'clearfix');
    $element['#attributes']['id'] = array('views-display-top');

    // Extra actions for the display
    $element['extra_actions'] = array(
      '#type' => 'dropbutton',
      '#attributes' => array(
        'id' => 'views-display-extra-actions',
      ),
      '#links' => array(
        'edit-details' => array(
697
          'title' => $this->t('Edit view name/description'),
698
          'href' => "admin/structure/views/nojs/edit-details/{$view->id()}/$display_id",
699 700 701
          'attributes' => array('class' => array('views-ajax-link')),
        ),
        'analyze' => array(
702
          'title' => $this->t('Analyze view'),
703
          'href' => "admin/structure/views/nojs/analyze/{$view->id()}/$display_id",
704 705
          'attributes' => array('class' => array('views-ajax-link')),
        ),
706 707
        'duplicate' => array(
          'title' => $this->t('Duplicate view'),
708
        ) + $view->urlInfo('duplicate-form')->toArray(),
709
        'reorder' => array(
710
          'title' => $this->t('Reorder displays'),
711
          'href' => "admin/structure/views/nojs/reorder-displays/{$view->id()}/$display_id",
712 713 714 715 716
          'attributes' => array('class' => array('views-ajax-link')),
        ),
      ),
    );

717 718 719
    if ($view->access('delete')) {
      $element['extra_actions']['#links']['delete'] = array(
        'title' => $this->t('Delete view'),
720
      ) + $view->urlInfo('delete-form')->toArray();
721 722
    }

723
    // Let other modules add additional links here.
724
    \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
725

726 727
    if (isset($view->type) && $view->type != $this->t('Default')) {
      if ($view->type == $this->t('Overridden')) {
728
        $element['extra_actions']['#links']['revert'] = array(
729
          'title' => $this->t('Revert view'),
730 731
          'href' => "admin/structure/views/view/{$view->id()}/revert",
          'query' => array('destination' => "admin/structure/views/view/{$view->id()}"),
732 733 734 735
        );
      }
      else {
        $element['extra_actions']['#links']['delete'] = array(
736
          'title' => $this->t('Delete view'),
737
          'href' => "admin/structure/views/view/{$view->id()}/delete",
738 739 740 741 742 743 744 745 746
        );
      }
    }

    // Determine the displays available for editing.
    if ($tabs = $this->getDisplayTabs($view)) {
      if ($display_id) {
        $tabs[$display_id]['#active'] = TRUE;
      }
747
      $tabs['#prefix'] = '<h2 class="visually-hidden">' . $this->t('Secondary tabs') . '</h2><ul id = "views-display-menu-tabs" class="tabs secondary">';
748 749 750 751 752
      $tabs['#suffix'] = '</ul>';
      $element['tabs'] = $tabs;
    }

    // Buttons for adding a new display.
753
    foreach (Views::fetchPluginNames('display', NULL, array($view->get('base_table'))) as $type => $label) {
754 755
      $element['add_display'][$type] = array(
        '#type' => 'submit',
756
        '#value' => $this->t('Add !display', array('!display' => $label)),
757
        '#limit_validation_errors' => array(),
758
        '#submit' => array('::submitDisplayAdd', '::submitDelayDestination'),
759 760 761 762
        '#attributes' => array('class' => array('add-display')),
        // Allow JavaScript to remove the 'Add ' prefix from the button label when
        // placing the button in a "Add" dropdown menu.
        '#process' => array_merge(array('views_ui_form_button_was_clicked'), element_info_property('submit', '#process', array())),
763
        '#values' => array($this->t('Add !display', array('!display' => $label)), $label),
764 765 766 767 768 769 770 771 772 773
      );
    }

    return $element;
  }

  /**
   * Submit handler for form buttons that do not complete a form workflow.
   *
   * The Edit View form is a multistep form workflow, but with state managed by
774
   * the TempStore rather than $form_state->setRebuild(). Without this
775 776 777 778 779
   * submit handler, buttons that add or remove displays would redirect to the
   * destination parameter (e.g., when the Edit View form is linked to from a
   * contextual link). This handler can be added to buttons whose form submission
   * should not yet redirect to the destination.
   */
780
  public function submitDelayDestination($form, FormStateInterface $form_state) {
781 782 783 784 785 786 787 788 789 790 791
    $request = $this->requestStack->getCurrentRequest();
    $destination = $request->query->get('destination');

    $redirect = $form_state->getRedirect();
    // If there is a destination, and redirects are not explicitly disabled, add
    // the destination as a query string to the redirect and suppress it for the
    // current request.
    if (isset($destination) && $redirect !== FALSE) {
      // Create a valid redirect if one does not exist already.
      if (!($redirect instanceof Url)) {
        $redirect = Url::createFromRequest($request);
792
      }
793 794 795

      // Add the current destination to the redirect unless one exists already.
      $options = $redirect->getOptions();
796 797
      if (!isset($options['query']['destination'])) {
        $options['query']['destination'] = $destination;
798
        $redirect->setOptions($options);
799
      }
800 801 802

      $form_state->setRedirectUrl($redirect);
      $request->query->remove('destination');
803 804 805 806 807 808
    }
  }

  /**
   * Submit handler to duplicate a display for a view.
   */
809
  public function submitDisplayDuplicate($form, FormStateInterface $form_state) {
810
    $view = $this->entity;
811
    $display_id = $this->displayID;
812 813 814

    // Create the new display.
    $displays = $view->get('display');
815 816
    $display = $view->getExecutable()->newDisplay($displays[$display_id]['display_plugin']);
    $new_display_id = $display->display['id'];
817 818 819 820 821 822
    $displays[$new_display_id] = $displays[$display_id];
    $displays[$new_display_id]['id'] = $new_display_id;
    $view->set('display', $displays);

    // By setting the current display the changed marker will appear on the new
    // display.
823
    $view->getExecutable()->current_display = $new_display_id;
824
    $view->cacheSet();
825 826

    // Redirect to the new display's edit page.
827
    $form_state->setRedirect('entity.view.edit_display_form', array(
828 829 830
      'view' => $view->id(),
      'display_id' => $new_display_id,
    ));
831 832 833 834 835
  }

  /**
   * Submit handler to add a display to a view.
   */
836
  public function submitDisplayAdd($form, FormStateInterface $form_state) {
837
    $view = $this->entity;
838
    // Create the new display.
839
    $parents = $form_state->getTriggeringElement()['#parents'];
840
    $display_type = array_pop($parents);
841 842
    $display = $view->getExecutable()->newDisplay($display_type);
    $display_id = $display->display['id'];
843 844
    // A new display got added so the asterisks symbol should appear on the new
    // display.
845
    $view->getExecutable()->current_display = $display_id;
846
    $view->cacheSet();
847 848

    // Redirect to the new display's edit page.
849
    $form_state->setRedirect('entity.view.edit_display_form', array(
850 851 852
      'view' => $view->id(),
      'display_id' => $display_id,
    ));
853 854
  }

855
  /**
856
   * Submit handler to Duplicate a display as another display type.
857
   */
858
  public function submitDuplicateDisplayAsType($form, FormStateInterface $form_state) {
859
    $view = $this->entity;
860
    $display_id = $this->displayID;
861 862

    // Create the new display.
863
    $parents = $form_state->getTriggeringElement()['#parents'];
864
    $display_type = array_pop($parents);
865 866
    $display = $view->getExecutable()->newDisplay($display_type);
    $new_display_id = $display->display['id'];
867 868 869 870
    $displays = $view->get('display');

    // Let the display title be generated by the addDisplay method and set the
    // right display plugin, but keep the rest from the original display.
871 872 873
    $display_duplicate = $displays[$display_id];
    unset($display_duplicate['display_title']);
    unset($display_duplicate['display_plugin']);
874

875
    $displays[$new_display_id] = NestedArray::mergeDeep($displays[$new_display_id], $display_duplicate);
876 877 878 879 880
    $displays[$new_display_id]['id'] = $new_display_id;
    $view->set('display', $displays);

    // By setting the current display the changed marker will appear on the new
    // display.
881
    $view->getExecutable()->current_display = $new_display_id;
882
    $view->cacheSet();
883 884

    // Redirect to the new display's edit page.
885
    $form_state->setRedirect('entity.view.edit_display_form', array(
886 887 888
      'view' => $view->id(),
      'display_id' => $new_display_id,
    ));
889 890
  }

891 892 893 894 895 896 897 898 899 900 901 902
  /**
   * Build a renderable array representing one option on the edit form.
   *
   * This function might be more logical as a method on an object, if a suitable
   * object emerges out of refactoring.
   */
  public function buildOptionForm(ViewUI $view, $id, $option, $display) {
    $option_build = array();
    $option_build['#theme'] = 'views_ui_display_tab_setting';

    $option_build['#description'] = $option['title'];

903
    $option_build['#link'] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
904 905 906 907

    $option_build['#links'] = array();
    if (!empty($option['links']) && is_array($option['links'])) {
      foreach ($option['links'] as $link_id => $link_value) {
908
        $option_build['#settings_links'][] = $view->getExecutable()->displayHandlers->get($display['id'])->optionLink($option['setting'], $link_id, 'views-button-configure', $link_value);
909 910 911
      }
    }

912
    if (!empty($view->getExecutable()->displayHandlers->get($display['id'])->options['defaults'][$id])) {
913 914 915 916 917
      $display_id = 'default';
      $option_build['#defaulted'] = TRUE;
    }
    else {
      $display_id = $display['id'];
918 919
      if (!$view->getExecutable()->displayHandlers->get($display['id'])->isDefaultDisplay()) {
        if ($view->getExecutable()->displayHandlers->get($display['id'])->defaultableSections($id)) {
920 921 922 923 924 925 926 927 928 929 930 931
          $option_build['#overridden'] = TRUE;
        }
      }
    }
    $option_build['#attributes']['class'][] = drupal_clean_css_identifier($display_id . '-' . $id);
    return $option_build;
  }

  /**
   * Add information about a section to a display.
   */
  public function getFormBucket(ViewUI $view, $type, $display) {
932
    $executable = $view->getExecutable();
933 934 935
    $executable->setDisplay($display['id']);
    $executable->initStyle();

936
    $types = $executable->getHandlerTypes();
937

938 939