ViewEditFormController.php 42.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains Drupal\views_ui\ViewEditFormController.
 */

namespace Drupal\views_ui;

10 11 12
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
13
use Drupal\Component\Utility\NestedArray;
14
use Drupal\views\ViewExecutable;
15 16 17 18
use Drupal\Core\Entity\EntityControllerInterface;
use Drupal\user\TempStoreFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
19 20 21 22

/**
 * Form controller for the Views edit form.
 */
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
class ViewEditFormController extends ViewFormControllerBase implements EntityControllerInterface {

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

  /**
   * The request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a new ViewEditFormController object.
   *
   * @param string $operation
   *   The name of the current operation.
   * @param \Drupal\user\TempStoreFactory $temp_store_factory
   *   The factory for the temp store object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   */
  public function __construct($operation, TempStoreFactory $temp_store_factory, Request $request) {
    parent::__construct($operation);

    $this->tempStore = $temp_store_factory->get('views');
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, $entity_type, array $entity_info, $operation = NULL) {
    return new static(
      $operation,
      $container->get('user.tempstore'),
      $container->get('request')
    );
  }
66 67 68 69

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::form().
   */
70 71
  public function form(array $form, array &$form_state) {
    $view = $this->entity;
72
    $display_id = $this->displayID;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    // Do not allow the form to be cached, because $form_state['view'] can become
    // 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:
    //   - Change $form_state['view'] to $form_state['temporary']['view'].
    //   - Add a #process function to initialize $form_state['temporary']['view']
    //     on cached form submissions.
    //   - Use form_load_include().
    $form_state['no_cache'] = TRUE;

    if ($display_id) {
      if (!$view->get('executable')->setDisplay($display_id)) {
        $form['#markup'] = t('Invalid display id @display', array('@display' => $display_id));
        return $form;
      }
    }

    $form['#tree'] = TRUE;

    $form['#attached']['library'][] = array('system', 'jquery.ui.tabs');
    $form['#attached']['library'][] = array('system', 'jquery.ui.dialog');
    $form['#attached']['library'][] = array('system', 'drupal.states');
    $form['#attached']['library'][] = array('system', 'drupal.tabledrag');

97 98 99 100
    if (!config('views.settings')->get('no_javascript')) {
      $form['#attached']['library'][] = array('views_ui', 'views_ui.admin');
    }

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    $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' => '',
    );
    $form['#prefix'] .= '<div class="views-edit-view views-admin clearfix">';
    $form['#suffix'] = '</div>' . $form['#suffix'];

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

122
    if ($view->isLocked()) {
123 124
      $form['locked'] = array(
        '#type' => 'container',
125
        '#attributes' => array('class' => array('view-locked', 'messages', 'messages--warning')),
126
        '#children' => 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>.', array('!user' => theme('username', array('account' => user_load($view->lock->owner))), '!age' => format_interval(REQUEST_TIME - $view->lock->updated), '!break' => url('admin/structure/views/view/' . $view->id() . '/break-lock'))),
127 128 129 130 131 132
        '#weight' => -10,
      );
    }
    else {
      $form['changed'] = array(
        '#type' => 'container',
133
        '#attributes' => array('class' => array('view-changed', 'messages', 'messages--warning')),
134
        '#children' => t('You have unsaved changes.'),
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        '#weight' => -10,
      );
      if (empty($view->changed)) {
        $form['changed']['#attributes']['class'][] = 'js-hide';
      }
    }

    $form['displays'] = array(
      '#prefix' => '<h1 class="unit-title clearfix">' . t('Displays') . '</h1>',
      '#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) {
      $form_state['display_id'] = $display_id;

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

      // Add a text that the display is disabled.
167 168
      if ($view->get('executable')->displayHandlers->has($display_id)) {
        if (!$view->get('executable')->displayHandlers->get($display_id)->isEnabled()) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
          $form['displays']['settings']['disabled']['#markup'] = t('This display is disabled.');
        }
      }

      // 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.
184 185

      if ($view->get('executable')->displayHandlers->has($display_id) && !$view->get('executable')->displayHandlers->get($display_id)->isEnabled()) {
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        $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(
        '#markup' => '<h2 id="views-ajax-title"></h2>',
      );
      $form['ajax-area']['ajax-body'] = array(
        '#type' => 'container',
        '#id' => 'views-ajax-body',
        '#children' => $view->getDefaultAJAXMessage(),
      );
    }

    return $form;
  }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::actions().
   */
  protected function actions(array $form, array &$form_state) {
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);

    $actions['cancel'] = array(
      '#value' => t('Cancel'),
      '#submit' => array(
        array($this, 'cancel'),
      ),
    );
    return $actions;
  }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::validate().
   */
  public function validate(array $form, array &$form_state) {
    parent::validate($form, $form_state);

233
    $view = $this->entity;
234 235
    foreach ($view->get('executable')->validate() as $display_errors) {
      foreach ($display_errors as $error) {
236 237 238 239 240 241 242 243 244 245 246
        form_set_error('', $error);
      }
    }
  }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::submit().
   */
  public function submit(array $form, array &$form_state) {
    parent::submit($form, $form_state);

247
    $view = $this->entity;
248 249 250 251
    // Go through and remove displayed scheduled for removal.
    $displays = $view->get('display');
    foreach ($displays as $id => $display) {
      if (!empty($display['deleted'])) {
252
        $view->get('executable')->displayHandlers->remove($id);
253 254 255 256 257 258 259
        unset($displays[$id]);
      }
    }
    // Rename display ids if needed.
    foreach ($view->get('executable')->displayHandlers as $id => $display) {
      if (!empty($display->display['new_id'])) {
        $new_id = $display->display['new_id'];
260 261
        $view->get('executable')->displayHandlers->set($new_id, $view->get('executable')->displayHandlers->get($id));
        $view->get('executable')->displayHandlers->get($new_id)->display['id'] = $new_id;
262 263 264 265

        $displays[$new_id] = $displays[$id];
        unset($displays[$id]);
        // Redirect the user to the renamed display to be sure that the page itself exists and doesn't throw errors.
266
        $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $new_id;
267 268 269 270 271
      }
    }
    $view->set('display', $displays);

    // @todo: Revisit this when http://drupal.org/node/1668866 is in.
272
    $query = $this->request->query;
273
    $destination = $query->get('destination');
274

275 276
    if (!empty($destination)) {
      // Find out the first display which has a changed path and redirect to this url.
277
      $old_view = views_get_view($view->id());
278 279 280 281 282 283 284 285
      $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;
        }

286 287
        if (($display->getPluginId() == 'page') && ($old_path == $destination) && ($old_path != $view->get('executable')->displayHandlers->get($id)->getOption('path'))) {
          $destination = $view->get('executable')->displayHandlers->get($id)->getOption('path');
288 289 290 291 292 293 294 295 296 297
          $query->remove('destination');
          // @todo For whatever reason drupal_goto is still using $_GET.
          // @see http://drupal.org/node/1668866
          unset($_GET['destination']);
        }
      }
      $form_state['redirect'] = $destination;
    }

    $view->save();
298
    drupal_set_message(t('The view %name has been saved.', array('%name' => $view->label())));
299 300

    // Remove this view from cache so we can edit it properly.
301
    $this->tempStore->delete($view->id());
302 303 304 305 306 307 308 309 310 311 312 313
  }

  /**
   * Form submission handler for the 'cancel' action.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function cancel(array $form, array &$form_state) {
    // Remove this view from cache so edits will be lost.
314
    $view = $this->entity;
315
    $this->tempStore->delete($view->id());
316 317 318 319 320 321 322 323
    $form_state['redirect'] = 'admin/structure/views';
  }

  /**
   * Returns a renderable array representing the edit page for one display.
   */
  public function getDisplayTab($view) {
    $build = array();
324
    $display_id = $this->displayID;
325
    $display = $view->get('executable')->displayHandlers->get($display_id);
326 327 328
    // If the plugin doesn't exist, display an error message instead of an edit
    // page.
    if (empty($display)) {
329
      $title = isset($display->display['display_title']) ? $display->display['display_title'] : t('Invalid');
330
      // @TODO: Improved UX for the case where a plugin is missing.
331
      $build['#markup'] = 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']));
332 333 334 335 336 337 338
    }
    // 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.
339
    \Drupal::moduleHandler()->alter('views_ui_display_tab', $build, $view, $display_id);
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    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']);
    // The master display cannot be cloned.
    $is_default = $display['id'] == 'default';
    // @todo: Figure out why getOption doesn't work here.
362
    $is_enabled = $view->get('executable')->displayHandlers->get($display['id'])->isEnabled();
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

    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',
382
            '#value' => t('Enable @display_title', array('@display_title' => $display_title)),
383 384 385 386 387 388
            '#limit_validation_errors' => array(),
            '#submit' => array(array($this, 'submitDisplayEnable'), array($this, 'submitDelayDestination')),
            '#prefix' => '<li class="enable">',
            "#suffix" => '</li>',
          );
        }
389 390 391
        // Add a link to view the page unless the view is disabled or has no
        // path.
        elseif ($view->status() && $view->get('executable')->displayHandlers->get($display['id'])->hasPath()) {
392
          $path = $view->get('executable')->displayHandlers->get($display['id'])->getPath();
393
          if ($path && (strpos($path, '%') === FALSE)) {
394 395
            $build['top']['actions']['path'] = array(
              '#type' => 'link',
396
              '#title' => t('View @display', array('@display' => $display['display_title'])),
397 398 399 400 401 402 403 404 405 406
              '#options' => array('alt' => array(t("Go to the real page for this display"))),
              '#href' => $path,
              '#prefix' => '<li class="view">',
              "#suffix" => '</li>',
            );
          }
        }
        if (!$is_default) {
          $build['top']['actions']['duplicate'] = array(
            '#type' => 'submit',
407
            '#value' => t('Clone @display_title', array('@display_title' => $display_title)),
408 409 410 411 412 413 414 415 416
            '#limit_validation_errors' => array(),
            '#submit' => array(array($this, 'submitDisplayDuplicate'), array($this, 'submitDelayDestination')),
            '#prefix' => '<li class="duplicate">',
            "#suffix" => '</li>',
          );
        }
        // Always allow a display to be deleted.
        $build['top']['actions']['delete'] = array(
          '#type' => 'submit',
417
          '#value' => t('Delete @display_title', array('@display_title' => $display_title)),
418 419 420 421 422
          '#limit_validation_errors' => array(),
          '#submit' => array(array($this, 'submitDisplayDelete'), array($this, 'submitDelayDestination')),
          '#prefix' => '<li class="delete">',
          "#suffix" => '</li>',
        );
423 424 425 426 427 428 429 430

        foreach (views_fetch_plugin_names('display', NULL, array($view->get('storage')->get('base_table'))) as $type => $label) {
          if ($type == $display['display_plugin']) {
            continue;
          }

          $build['top']['actions']['clone_as'][$type] = array(
            '#type' => 'submit',
431
            '#value' => t('Clone as @type', array('@type' => $label)),
432 433 434 435 436 437
            '#limit_validation_errors' => array(),
            '#submit' => array(array($this, 'submitCloneDisplayAsType'), array($this, 'submitDelayDestination')),
            '#prefix' => '<li class="duplicate">',
            '#suffix' => '</li>',
          );
        }
438 439 440 441
      }
      else {
        $build['top']['actions']['undo_delete'] = array(
          '#type' => 'submit',
442
          '#value' => t('Undo delete of @display_title', array('@display_title' => $display_title)),
443 444 445 446 447 448
          '#limit_validation_errors' => array(),
          '#submit' => array(array($this, 'submitDisplayUndoDelete'), array($this, 'submitDelayDestination')),
          '#prefix' => '<li class="undo-delete">',
          "#suffix" => '</li>',
        );
      }
449 450 451
      if ($is_enabled) {
        $build['top']['actions']['disable'] = array(
          '#type' => 'submit',
452
          '#value' => t('Disable @display_title', array('@display_title' => $display_title)),
453 454 455 456 457 458
          '#limit_validation_errors' => array(),
          '#submit' => array(array($this, 'submitDisplayDisable'), array($this, 'submitDelayDestination')),
          '#prefix' => '<li class="disable">',
          "#suffix" => '</li>',
        );
      }
459 460 461 462 463 464
      $build['top']['actions']['suffix']['#markup'] = '</ul>';

      // The area above the three columns.
      $build['top']['display_title'] = array(
        '#theme' => 'views_ui_display_tab_setting',
        '#description' => t('Display name'),
465
        '#link' => $view->get('executable')->displayHandlers->get($display['id'])->optionLink(check_plain($display_title), 'display_title'),
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
      );
    }

    $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();
482
    $build['columns']['second']['empty'] = array();
483 484
    $build['columns']['second']['pager'] = array();

485
    // The third column buckets are wrapped in details.
486
    $build['columns']['third'] = array(
487
      '#type' => 'details',
488
      '#title' => t('Advanced'),
489
      '#theme_wrappers' => array('details', 'container'),
490 491 492 493 494 495 496 497
      '#attributes' => array(
        'class' => array(
          'views-display-column',
          'third',
        ),
      ),
    );

498
    // Collapse the details by default.
499
    $build['columns']['third']['#open'] = config('views.settings')->get('ui.show.advanced_column');
500 501 502 503 504 505 506

    // 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();
507
    $view->get('executable')->displayHandlers->get($display['id'])->optionsSummary($buckets, $options);
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

    // 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);
539
    $build['columns']['second']['empty'] = $this->getFormBucket($view, 'empty', $display);
540 541 542 543 544 545 546 547 548 549
    $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.
   */
  public function submitDisplayUndoDelete($form, &$form_state) {
550
    $view = $this->entity;
551 552 553 554 555 556 557
    // Create the new display
    $id = $form_state['display_id'];
    $displays = $view->get('display');
    $displays[$id]['deleted'] = FALSE;
    $view->set('display', $displays);

    // Store in cache
558
    $view->cacheSet();
559 560

    // Redirect to the top-level edit page.
561
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $id;
562 563 564 565 566 567
  }

  /**
   * Submit handler to enable a disabled display.
   */
  public function submitDisplayEnable($form, &$form_state) {
568
    $view = $this->entity;
569 570
    $id = $form_state['display_id'];
    // setOption doesn't work because this would might affect upper displays
571
    $view->get('executable')->displayHandlers->get($id)->setOption('enabled', TRUE);
572 573

    // Store in cache
574
    $view->cacheSet();
575 576

    // Redirect to the top-level edit page.
577
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $id;
578 579 580 581 582 583
  }

  /**
   * Submit handler to disable display.
   */
  public function submitDisplayDisable($form, &$form_state) {
584
    $view = $this->entity;
585
    $id = $form_state['display_id'];
586
    $view->get('executable')->displayHandlers->get($id)->setOption('enabled', FALSE);
587 588

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

    // Redirect to the top-level edit page.
592
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $id;
593 594 595 596 597 598
  }

  /**
   * Submit handler to delete a display from a view.
   */
  public function submitDisplayDelete($form, &$form_state) {
599
    $view = $this->entity;
600 601 602 603 604 605
    $display_id = $form_state['display_id'];

    // Mark the display for deletion.
    $displays = $view->get('display');
    $displays[$display_id]['deleted'] = TRUE;
    $view->set('display', $displays);
606
    $view->cacheSet();
607 608 609

    // Redirect to the top-level edit page. The first remaining display will
    // become the active display.
610
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id();
611 612 613 614
  }

  /**
   * Regenerate the current tab for AJAX updates.
615 616 617 618 619 620 621
   *
   * @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.
622
   */
623
  public function rebuildCurrentTab(ViewUI $view, AjaxResponse $response, $display_id) {
624
    $this->displayID = $display_id;
625 626 627 628 629
    if (!$view->get('executable')->setDisplay('default')) {
      return;
    }

    // Regenerate the main display area.
630
    $build = $this->getDisplayTab($view);
631
    static::addMicroweights($build);
632
    $response->addCommand(new HtmlCommand('#views-tab-' . $display_id, drupal_render($build)));
633 634 635 636

    // Regenerate the top area so changes to display names and order will appear.
    $build = $this->renderDisplayTop($view);
    static::addMicroweights($build);
637
    $response->addCommand(new ReplaceCommand('#views-display-top', drupal_render($build)));
638 639 640 641 642 643
  }

  /**
   * Render the top of the display so it can be updated during ajax operations.
   */
  public function renderDisplayTop(ViewUI $view) {
644
    $display_id = $this->displayID;
645
    $element['#theme_wrappers'][] = 'views_ui_container';
646 647 648 649 650 651 652 653 654 655 656
    $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(
657
          'title' => t('Edit view name/description'),
658
          'href' => "admin/structure/views/nojs/edit-details/{$view->id()}/$display_id",
659 660 661
          'attributes' => array('class' => array('views-ajax-link')),
        ),
        'analyze' => array(
662
          'title' => t('Analyze view'),
663
          'href' => "admin/structure/views/nojs/analyze/{$view->id()}/$display_id",
664 665 666
          'attributes' => array('class' => array('views-ajax-link')),
        ),
        'clone' => array(
667
          'title' => t('Clone view'),
668
          'href' => "admin/structure/views/view/{$view->id()}/clone",
669 670
        ),
        'reorder' => array(
671
          'title' => t('Reorder displays'),
672
          'href' => "admin/structure/views/nojs/reorder-displays/{$view->id()}/$display_id",
673 674 675 676 677 678
          'attributes' => array('class' => array('views-ajax-link')),
        ),
      ),
    );

    // Let other modules add additional links here.
679
    \Drupal::moduleHandler()->alter('views_ui_display_top_links', $element['extra_actions']['#links'], $view, $display_id);
680 681 682 683

    if (isset($view->type) && $view->type != t('Default')) {
      if ($view->type == t('Overridden')) {
        $element['extra_actions']['#links']['revert'] = array(
684
          'title' => t('Revert view'),
685 686
          'href' => "admin/structure/views/view/{$view->id()}/revert",
          'query' => array('destination' => "admin/structure/views/view/{$view->id()}"),
687 688 689 690
        );
      }
      else {
        $element['extra_actions']['#links']['delete'] = array(
691
          'title' => t('Delete view'),
692
          'href' => "admin/structure/views/view/{$view->id()}/delete",
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
        );
      }
    }

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

    // Buttons for adding a new display.
    foreach (views_fetch_plugin_names('display', NULL, array($view->get('base_table'))) as $type => $label) {
      $element['add_display'][$type] = array(
        '#type' => 'submit',
        '#value' => t('Add !display', array('!display' => $label)),
        '#limit_validation_errors' => array(),
        '#submit' => array(array($this, 'submitDisplayAdd'), array($this, 'submitDelayDestination')),
        '#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())),
        '#values' => array(t('Add !display', array('!display' => $label)), $label),
      );
    }

    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
   * the TempStore rather than $form_state['rebuild']. Without this
   * 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.
   */
  public function submitDelayDestination($form, &$form_state) {
736
    $query = $this->request->query;
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    // @todo: Revisit this when http://drupal.org/node/1668866 is in.
    $destination = $query->get('destination');
    if (isset($destination) && $form_state['redirect'] !== FALSE) {
      if (!isset($form_state['redirect'])) {
        $form_state['redirect'] = current_path();
      }
      if (is_string($form_state['redirect'])) {
        $form_state['redirect'] = array($form_state['redirect']);
      }
      $options = isset($form_state['redirect'][1]) ? $form_state['redirect'][1] : array();
      if (!isset($options['query']['destination'])) {
        $options['query']['destination'] = $destination;
      }
      $form_state['redirect'][1] = $options;
      $query->remove('destination');
    }
  }

  /**
   * Submit handler to duplicate a display for a view.
   */
  public function submitDisplayDuplicate($form, &$form_state) {
759
    $view = $this->entity;
760
    $display_id = $this->displayID;
761 762 763 764 765 766 767 768 769 770 771

    // Create the new display.
    $displays = $view->get('display');
    $new_display_id = $view->addDisplay($displays[$display_id]['display_plugin']);
    $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.
    $view->get('executable')->current_display = $new_display_id;
772
    $view->cacheSet();
773 774

    // Redirect to the new display's edit page.
775
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $new_display_id;
776 777 778 779 780 781
  }

  /**
   * Submit handler to add a display to a view.
   */
  public function submitDisplayAdd($form, &$form_state) {
782
    $view = $this->entity;
783 784 785 786 787 788 789
    // Create the new display.
    $parents = $form_state['triggering_element']['#parents'];
    $display_type = array_pop($parents);
    $display_id = $view->addDisplay($display_type);
    // A new display got added so the asterisks symbol should appear on the new
    // display.
    $view->get('executable')->current_display = $display_id;
790
    $view->cacheSet();
791 792

    // Redirect to the new display's edit page.
793
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $display_id;
794 795
  }

796 797 798 799
  /**
   * Submit handler to clone a display as another display type.
   */
  public function submitCloneDisplayAsType($form, &$form_state) {
800
    $view = $this->entity;
801
    $display_id = $this->displayID;
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

    // Create the new display.
    $parents = $form_state['triggering_element']['#parents'];
    $display_type = array_pop($parents);
    $new_display_id = $view->addDisplay($display_type);
    $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.
    $display_clone = $displays[$display_id];
    unset($display_clone['display_title']);
    unset($display_clone['display_plugin']);

    $displays[$new_display_id] = NestedArray::mergeDeep($displays[$new_display_id], $display_clone);
    $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.
    $view->get('executable')->current_display = $new_display_id;
822
    $view->cacheSet();
823 824 825 826 827

    // Redirect to the new display's edit page.
    $form_state['redirect'] = 'admin/structure/views/view/' . $view->id() . '/edit/' . $new_display_id;
  }

828 829 830 831 832 833 834 835 836 837 838 839
  /**
   * 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'];

840
    $option_build['#link'] = $view->get('executable')->displayHandlers->get($display['id'])->optionLink($option['value'], $id, '', empty($option['desc']) ? '' : $option['desc']);
841 842 843 844

    $option_build['#links'] = array();
    if (!empty($option['links']) && is_array($option['links'])) {
      foreach ($option['links'] as $link_id => $link_value) {
845
        $option_build['#settings_links'][] = $view->get('executable')->displayHandlers->get($display['id'])->optionLink($option['setting'], $link_id, 'views-button-configure', $link_value);
846 847 848
      }
    }

849
    if (!empty($view->get('executable')->displayHandlers->get($display['id'])->options['defaults'][$id])) {
850 851 852 853 854
      $display_id = 'default';
      $option_build['#defaulted'] = TRUE;
    }
    else {
      $display_id = $display['id'];
855 856
      if (!$view->get('executable')->displayHandlers->get($display['id'])->isDefaultDisplay()) {
        if ($view->get('executable')->displayHandlers->get($display['id'])->defaultableSections($id)) {
857 858 859 860 861 862 863 864 865 866 867 868
          $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) {
869 870 871 872 873 874
    $executable = $view->get('executable');
    $executable->setDisplay($display['id']);
    $executable->initStyle();

    $types = $executable->viewsHandlerTypes();

875 876 877 878 879 880 881 882 883
    $build = array(
      '#theme_wrappers' => array('views_ui_display_tab_bucket'),
    );

    $build['#overridden'] = FALSE;
    $build['#defaulted'] = FALSE;

    $build['#name'] = $build['#title'] = $types[$type]['title'];

884
    $rearrange_url = "admin/structure/views/nojs/rearrange/{$view->id()}/{$display['id']}/$type";
885 886 887
    $rearrange_text = t('Rearrange');
    $class = 'icon compact rearrange';

888 889 890 891
    // Different types now have different rearrange forms, so we use this switch
    // to get the right one.
    switch ($type) {
      case 'filter':
892 893
        // The rearrange form for filters contains the and/or UI, so override
        // the used path.
894
        $rearrange_url = "admin/structure/views/nojs/rearrange-filter/{$view->id()}/{$display['id']}";
895 896 897 898 899 900
        $rearrange_text = t('And/Or, Rearrange');
        // TODO: Add another class to have another symbol for filter rearrange.
        $class = 'icon compact rearrange';
        break;
      case 'field':
        // Fetch the style plugin info so we know whether to list fields or not.
901
        $style_plugin = $executable->style_plugin;
902 903 904 905 906 907 908 909 910
        $uses_fields = $style_plugin && $style_plugin->usesFields();
        if (!$uses_fields) {
          $build['fields'][] = array(
            '#markup' => t('The selected style or row format does not utilize fields.'),
            '#theme_wrappers' => array('views_ui_container'),
            '#attributes' => array('class' => array('views-display-setting')),
          );
          return $build;
        }
911
        break;
912 913 914
      case 'header':
      case 'footer':
      case 'empty':
915
        if (!$executable->display_handler->usesAreas()) {
916 917 918 919 920 921 922
          $build[$type][] = array(
            '#markup' => t('The selected display type does not utilize @type plugins', array('@type' => $type)),
            '#theme_wrappers' => array('views_ui_container'),
            '#attributes' => array('class' => array('views-display-setting')),
          );
          return $build;
        }
923
        break;
924 925 926 927
    }

    // Create an array of actions to pass to theme_links
    $actions = array();
928
    $count_handlers = count($executable->display_handler->getHandlers($type));
929 930 931 932

    // Create the add text variable for the add action.
    $add_text = t('Add <span class="element-invisible">@type</span>', array('@type' => $types[$type]['ltitle']));

933
    $actions['add'] = array(
934
      'title' => $add_text,
935
      'href' => "admin/structure/views/nojs/add-item/{$view->id()}/{$display['id']}/$type",
936
      'attributes' => array('class' => array('icon compact add', 'views-ajax-link'), 'id' => 'views-add-' . $type),
937 938 939
      'html' => TRUE,
    );
    if ($count_handlers > 0) {
940 941 942
      // Create the rearrange text variable for the rearrange action.
      $rearrange_text = $type == 'filter' ? t('And/Or Rearrange <span class="element-invisible">filter criteria</span>') : t('Rearrange <span class="element-invisible">@type</span>', array('@type' => $types[$type]['ltitle']));

943 944 945
      $actions['rearrange'] = array(
        'title' => $rearrange_text,
        'href' => $rearrange_url,
946
        'attributes' => array('class' => array($class, 'views-ajax-link'), 'id' => 'views-rearrange-' . $type),
947 948 949 950 951 952 953 954 955 956 957 958 959
        'html' => TRUE,
      );
    }

    // Render the array of links
    $build['#actions'] = array(
      '#type' => 'dropbutton',
      '#links' => $actions,
      '#attributes' => array(
        'class' => array('views-ui-settings-bucket-operations'),
      ),
    );

960 961
    if (!$executable->display_handler->isDefaultDisplay()) {
      if (!$executable->display_handler->isDefaulted($types[$type]['plural'])) {
962 963 964 965 966 967 968 969 970
        $build['#overridden'] = TRUE;
      }
      else {
        $build['#defaulted'] = TRUE;
      }
    }

    static $relationships = NULL;
    if (!isset($relationships)) {
971
      // Get relationship labels.
972
      $relationships = array();
973
      foreach ($executable->display_handler->getHandlers('relationship') as $id => $handler) {
974
        $relationships[$id] = $handler->adminLabel();
975 976 977 978 979 980 981
      }
    }

    // Filters can now be grouped so we do a little bit extra:
    $groups = array();
    $grouping = FALSE;
    if ($type == 'filter') {
982
      $group_info = $executable->display_handler->getOption('filter_groups');
983 984 985 986 987 988 989 990 991 992 993
      // If there is only one group but it is using the "OR" filter, we still
      // treat it as a group for display purposes, since we want to display the
      // "OR" label next to items within the group.
      if (!empty($group_info['groups']) && (count($group_info['groups']) > 1 || current($group_info['groups']) == 'OR')) {
        $grouping = TRUE;
        $groups = array(0 => array());
      }
    }

    $build['fields'] = array();

994
    foreach ($executable->display_handler->getOption($types[$type]['plural']) as $id => $field) {
995 996 997 998
      // Build the option link for this handler ("Node: ID = article").
      $build['fields'][$id] = array();
      $build['fields'][$id]['#theme'] = 'views_ui_display_tab_setting';

999
      $handler = $executable->display_handler->getHandler($type, $id);
1000 1001 1002
      if (empty($handler)) {
        $build['fields'][$id]['#class'][] = 'broken';
        $field_name = t('Broken/missing handler: @table > @field', array('@table' => $field['table'], '@field' => $field['field']));
1003
        $build['fields'][$id]['#link'] = l($field_name, "admin/structure/views/nojs/config-item/{$view->id()}/{$display['id']}/$type/$id", array('attributes' => array('class' => array('views-ajax-link')), 'html' => TRUE));
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        continue;
      }

      $field_name = check_plain($handler->adminLabel(TRUE));
      if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
        $field_name = '(' . $relationships[$field['relationship']] . ') ' . $field_name;
      }

      $description = filter_xss_admin($handler->adminSummary());
      $link_text = $field_name . (empty($description) ? '' : " ($description)");
      $link_attributes = array('class' => array('views-ajax-link'));
      if (!empty($field['exclude'])) {
        $link_attributes['class'][] = 'views-field-excluded';
      }
1018
      $build['fields'][$id]['#link'] = l($link_text, "admin/structure/views/nojs/config-item/{$view->id()}/{$display['id']}/$type/$id", array('attributes' => $link_attributes, 'html' => TRUE));
1019 1020
      $build['fields'][$id]['#class'][] = drupal_clean_css_identifier($display['id']. '-' . $type . '-' . $id);

1021
      if ($executable->display_handler->useGroupBy() && $handler->usesGroupBy()) {
1022
        $build['fields'][$id]['#settings_links'][] = l('<span class="label">' . t('Aggregation settings') . '</span>', "admin/structure/views/nojs/config-item-group/{$view->id()}/{$display['id']}/$type/$id", array('attributes' => array('class' => 'views-button-configure views-ajax-link', 'title' => t('Aggregation settings')), 'html' => TRUE));
1023 1024 1025
      }

      if ($handler->hasExtraOptions()) {
1026
        $build['fields'][$id]['#settings_links'][] = l('<span class="label">' . t('Settings') . '</span>', "admin/structure/views/nojs/config-item-extra/{$view->id()}/{$display['id']}/$type/$id", array('attributes' => array('class' => array('views-button-configure', 'views-ajax-link'), 'title' => t('Settings')), 'html' => TRUE));
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
      }

      if ($grouping) {
        $gid = $handler->options['group'];

        // Show in default group if the group does not exist.
        if (empty($group_info['groups'][$gid])) {
          $gid = 0;
        }
        $groups[$gid][] = $id;
      }
    }

    // If using grouping, re-order fields so that they show up properly in the list.
    if ($type == 'filter' && $grouping) {
      $store = $build['fields'];
      $build['fields'] = array();
      foreach ($groups as $gid => $contents) {
        // Display an operator between each group.
        if (!empty($build['fields'])) {
          $build['fields'][] = array(
            '#theme' => 'views_ui_display_tab_setting',
            '#class' => array('views-group-text'),
            '#link' => ($group_info['operator'] == 'OR' ? t('OR') : t('AND')),
          );
        }
        // Display an operator between each pair of filters within the group.
        $keys = array_keys($contents);
        $last = end($keys);
        foreach ($contents as $key => $pid) {
          if ($key != $last) {
            $store[$pid]['#link'] .= '&nbsp;&nbsp;' . ($group_info['groups'][$gid] == 'OR' ? t('OR') : t('AND'));
          }
          $build['fields'][$pid] = $store[$pid];
        }
      }
    }

    return $build;
  }

  /**
   * Recursively adds microweights to a render array, similar to what form_builder() does for forms.
   *
   * @todo Submit a core patch to fix drupal_render() to do this, so that all
   *   render arrays automatically preserve array insertion order, as forms do.
   */
  public static function addMicroweights(&$build) {
    $count = 0;
    foreach (element_children($build) as $key) {
      if (!isset($build[$key]['#weight'])) {
        $build[$key]['#weight'] = $count/1000;
      }
      static::addMicroweights($build[$key]);
      $count++;
    }
  }

}