ExposedFormPluginBase.php 11.9 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2
<?php

3
namespace Drupal\views\Plugin\views\exposed_form;
4

5
use Drupal\Component\Utility\Html;
6 7
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
8 9
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\views\Plugin\views\PluginBase;
11

merlinofchaos's avatar
merlinofchaos committed
12
/**
13
 * Base class for Views exposed filter form plugins.
14 15
 *
 * @ingroup views_exposed_form_plugins
merlinofchaos's avatar
merlinofchaos committed
16
 */
17
abstract class ExposedFormPluginBase extends PluginBase implements CacheableDependencyInterface, ExposedFormPluginInterface {
merlinofchaos's avatar
merlinofchaos committed
18

19
  /**
20
   * {@inheritdoc}
21
   */
22
  protected $usesOptions = TRUE;
23

24 25 26
  /**
   * {@inheritdoc}
   */
27 28
  protected function defineOptions() {
    $options = parent::defineOptions();
29
    $options['submit_button'] = array('default' => $this->t('Apply'));
30
    $options['reset_button'] = array('default' => FALSE);
31 32
    $options['reset_button_label'] = array('default' => $this->t('Reset'));
    $options['exposed_sorts_label'] = array('default' => $this->t('Sort by'));
33
    $options['expose_sort_order'] = array('default' => TRUE);
34 35
    $options['sort_asc_label'] = array('default' => $this->t('Asc'));
    $options['sort_desc_label'] = array('default' => $this->t('Desc'));
merlinofchaos's avatar
merlinofchaos committed
36 37 38
    return $options;
  }

39 40 41
  /**
   * {@inheritdoc}
   */
42
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
43
    parent::buildOptionsForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
44 45
    $form['submit_button'] = array(
      '#type' => 'textfield',
46
      '#title' => $this->t('Submit button text'),
merlinofchaos's avatar
merlinofchaos committed
47 48 49 50
      '#default_value' => $this->options['submit_button'],
      '#required' => TRUE,
    );

51
    $form['reset_button'] = array(
merlinofchaos's avatar
merlinofchaos committed
52
      '#type' => 'checkbox',
53
      '#title' => $this->t('Include reset button (resets all applied exposed filters)'),
merlinofchaos's avatar
merlinofchaos committed
54 55 56 57 58
      '#default_value' => $this->options['reset_button'],
    );

    $form['reset_button_label'] = array(
     '#type' => 'textfield',
59 60
      '#title' => $this->t('Reset button label'),
      '#description' => $this->t('Text to display in the reset button of the exposed form.'),
merlinofchaos's avatar
merlinofchaos committed
61 62
      '#default_value' => $this->options['reset_button_label'],
      '#required' => TRUE,
63 64 65 66
      '#states' => array(
        'invisible' => array(
          'input[name="exposed_form_options[reset_button]"]' => array('checked' => FALSE),
        ),
merlinofchaos's avatar
merlinofchaos committed
67 68 69 70 71
      ),
    );

    $form['exposed_sorts_label'] = array(
      '#type' => 'textfield',
72
      '#title' => $this->t('Exposed sorts label'),
merlinofchaos's avatar
merlinofchaos committed
73 74 75 76
      '#default_value' => $this->options['exposed_sorts_label'],
      '#required' => TRUE,
    );

77 78
    $form['expose_sort_order'] = array(
      '#type' => 'checkbox',
79 80
      '#title' => $this->t('Allow people to choose the sort order'),
      '#description' => $this->t('If sort order is not exposed, the sort criteria settings for each sort will determine its order.'),
81 82 83
      '#default_value' => $this->options['expose_sort_order'],
    );

merlinofchaos's avatar
merlinofchaos committed
84 85
    $form['sort_asc_label'] = array(
      '#type' => 'textfield',
86
      '#title' => $this->t('Label for ascending sort'),
merlinofchaos's avatar
merlinofchaos committed
87 88
      '#default_value' => $this->options['sort_asc_label'],
      '#required' => TRUE,
89 90 91 92 93
      '#states' => array(
        'visible' => array(
          'input[name="exposed_form_options[expose_sort_order]"]' => array('checked' => TRUE),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
94 95 96 97
    );

    $form['sort_desc_label'] = array(
      '#type' => 'textfield',
98
      '#title' => $this->t('Label for descending sort'),
merlinofchaos's avatar
merlinofchaos committed
99 100
      '#default_value' => $this->options['sort_desc_label'],
      '#required' => TRUE,
101 102 103 104 105
      '#states' => array(
        'visible' => array(
          'input[name="exposed_form_options[expose_sort_order]"]' => array('checked' => TRUE),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
106 107 108 109
    );
  }

  /**
110
   * {@inheritdoc}
merlinofchaos's avatar
merlinofchaos committed
111
   */
112
  public function renderExposedForm($block = FALSE) {
merlinofchaos's avatar
merlinofchaos committed
113
    // Deal with any exposed filters we may have, before building.
114 115 116 117 118 119 120 121 122
    $form_state = (new FormState())
      ->setStorage([
        'view' => $this->view,
        'display' => &$this->view->display_handler->display,
        'rerender' => TRUE,
      ])
      ->setMethod('get')
      ->setAlwaysProcess()
      ->disableRedirect();
merlinofchaos's avatar
merlinofchaos committed
123 124 125 126

    // Some types of displays (eg. attachments) may wish to use the exposed
    // filters of their parent displays instead of showing an additional
    // exposed filter form for the attachment as well as that for the parent.
127
    if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
128
      $form_state->set('rerender', NULL);
merlinofchaos's avatar
merlinofchaos committed
129 130 131
    }

    if (!empty($this->ajax)) {
132
      $form_state->set('ajax', TRUE);
merlinofchaos's avatar
merlinofchaos committed
133 134
    }

135
    $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
merlinofchaos's avatar
merlinofchaos committed
136

137
    if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
138
      return array();
merlinofchaos's avatar
merlinofchaos committed
139 140
    }
    else {
141
      return $form;
merlinofchaos's avatar
merlinofchaos committed
142 143 144
    }
  }

145 146 147
  /**
   * {@inheritdoc}
   */
148
  public function query() {
merlinofchaos's avatar
merlinofchaos committed
149 150 151 152 153 154 155 156 157
    $view = $this->view;
    $exposed_data = isset($view->exposed_data) ? $view->exposed_data : array();
    $sort_by = isset($exposed_data['sort_by']) ? $exposed_data['sort_by'] : NULL;
    if (!empty($sort_by)) {
      // Make sure the original order of sorts is preserved
      // (e.g. a sticky sort is often first)
      if (isset($view->sort[$sort_by])) {
        $view->query->orderby = array();
        foreach ($view->sort as $key => $sort) {
158
          if (!$sort->isExposed()) {
merlinofchaos's avatar
merlinofchaos committed
159 160
            $sort->query();
          }
161
          elseif ($key == $sort_by) {
merlinofchaos's avatar
merlinofchaos committed
162 163 164
            if (isset($exposed_data['sort_order']) && in_array($exposed_data['sort_order'], array('ASC', 'DESC'))) {
              $sort->options['order'] = $exposed_data['sort_order'];
            }
165
            $sort->setRelationship();
merlinofchaos's avatar
merlinofchaos committed
166 167 168 169 170 171 172
            $sort->query();
          }
        }
      }
    }
  }

173 174 175
  /**
   * {@inheritdoc}
   */
176
  public function preRender($values) { }
merlinofchaos's avatar
merlinofchaos committed
177

178 179 180
  /**
   * {@inheritdoc}
   */
181
  public function postRender(&$output) { }
merlinofchaos's avatar
merlinofchaos committed
182

183 184 185
  /**
   * {@inheritdoc}
   */
186
  public function preExecute() { }
merlinofchaos's avatar
merlinofchaos committed
187

188 189 190
  /**
   * {@inheritdoc}
   */
191
  public function postExecute() { }
merlinofchaos's avatar
merlinofchaos committed
192

193
  /**
194
   * {@inheritdoc}
195
   */
196
  public function exposedFormAlter(&$form, FormStateInterface $form_state) {
197 198 199 200
    if (!empty($this->options['submit_button'])) {
      $form['actions']['submit']['#value'] = $this->options['submit_button'];
    }

merlinofchaos's avatar
merlinofchaos committed
201 202 203
    // Check if there is exposed sorts for this view
    $exposed_sorts = array();
    foreach ($this->view->sort as $id => $handler) {
204
      if ($handler->canExpose() && $handler->isExposed()) {
205
        $exposed_sorts[$id] = Html::escape($handler->options['expose']['label']);
merlinofchaos's avatar
merlinofchaos committed
206 207 208 209 210 211 212 213 214 215 216 217 218
      }
    }

    if (count($exposed_sorts)) {
      $form['sort_by'] = array(
        '#type' => 'select',
        '#options' => $exposed_sorts,
        '#title' => $this->options['exposed_sorts_label'],
      );
      $sort_order = array(
        'ASC' => $this->options['sort_asc_label'],
        'DESC' => $this->options['sort_desc_label'],
      );
219 220 221
      $user_input = $form_state->getUserInput();
      if (isset($user_input['sort_by']) && isset($this->view->sort[$user_input['sort_by']])) {
        $default_sort_order = $this->view->sort[$user_input['sort_by']]->options['order'];
222 223
      }
      else {
merlinofchaos's avatar
merlinofchaos committed
224 225 226 227
        $first_sort = reset($this->view->sort);
        $default_sort_order = $first_sort->options['order'];
      }

228
      if (!isset($user_input['sort_by'])) {
merlinofchaos's avatar
merlinofchaos committed
229
        $keys = array_keys($exposed_sorts);
230 231
        $user_input['sort_by'] = array_shift($keys);
        $form_state->setUserInput($user_input);
merlinofchaos's avatar
merlinofchaos committed
232 233
      }

234 235 236 237
      if ($this->options['expose_sort_order']) {
        $form['sort_order'] = array(
          '#type' => 'select',
          '#options' => $sort_order,
238
          '#title' => $this->t('Order', array(), array('context' => 'Sort order')),
239 240 241
          '#default_value' => $default_sort_order,
        );
      }
merlinofchaos's avatar
merlinofchaos committed
242
      $form['submit']['#weight'] = 10;
243 244 245
    }

    if (!empty($this->options['reset_button'])) {
246
      $form['actions']['reset'] = array(
247 248 249 250 251 252
        '#value' => $this->options['reset_button_label'],
        '#type' => 'submit',
        '#weight' => 10,
      );

      // Get an array of exposed filters, keyed by identifier option.
253
      $exposed_filters = [];
254 255 256 257 258 259 260 261
      foreach ($this->view->filter as $id => $handler) {
        if ($handler->canExpose() && $handler->isExposed() && !empty($handler->options['expose']['identifier'])) {
          $exposed_filters[$handler->options['expose']['identifier']] = $id;
        }
      }
      $all_exposed = array_merge($exposed_sorts, $exposed_filters);

      // Set the access to FALSE if there is no exposed input.
262
      if (!array_intersect_key($all_exposed, $this->view->getExposedInput())) {
263
        $form['actions']['reset']['#access'] = FALSE;
merlinofchaos's avatar
merlinofchaos committed
264 265 266
      }
    }

267
    $pager = $this->view->display_handler->getPlugin('pager');
merlinofchaos's avatar
merlinofchaos committed
268
    if ($pager) {
269
      $pager->exposedFormAlter($form, $form_state);
270
      $form_state->set('pager_plugin', $pager);
merlinofchaos's avatar
merlinofchaos committed
271 272 273
    }
  }

274 275 276
  /**
   * {@inheritdoc}
   */
277
  public function exposedFormValidate(&$form, FormStateInterface $form_state) {
278 279
    if ($pager_plugin = $form_state->get('pager_plugin')) {
      $pager_plugin->exposedFormValidate($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
280 281 282 283
    }
  }

  /**
284
   * {@inheritdoc}
285
   */
286
  public function exposedFormSubmit(&$form, FormStateInterface $form_state, &$exclude) {
287
    if (!$form_state->isValueEmpty('op') && $form_state->getValue('op') == $this->options['reset_button_label']) {
288
      $this->resetForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
289
    }
290 291
    if ($pager_plugin = $form_state->get('pager_plugin')) {
      $pager_plugin->exposedFormSubmit($form, $form_state, $exclude);
merlinofchaos's avatar
merlinofchaos committed
292 293 294 295
      $exclude[] = 'pager_plugin';
    }
  }

296 297 298 299 300 301 302 303 304 305 306
  /**
   * Resets all the states of the exposed form.
   *
   * This method is called when the "Reset" button is triggered. Clears
   * user inputs, stored session, and the form state.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
307
  public function resetForm(&$form, FormStateInterface $form_state) {
merlinofchaos's avatar
merlinofchaos committed
308 309 310 311 312 313
    // _SESSION is not defined for users who are not logged in.

    // If filters are not overridden, store the 'remember' settings on the
    // default display. If they are, store them on this display. This way,
    // multiple displays in the same view can share the same filters and
    // remember settings.
314
    $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
merlinofchaos's avatar
merlinofchaos committed
315

316 317
    if (isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
      unset($_SESSION['views'][$this->view->storage->id()][$display_id]);
merlinofchaos's avatar
merlinofchaos committed
318 319 320
    }

    // Set the form to allow redirect.
321
    if (empty($this->view->live_preview) && !\Drupal::request()->isXmlHttpRequest()) {
322
      $form_state->disableRedirect(FALSE);
merlinofchaos's avatar
merlinofchaos committed
323 324
    }
    else {
325
      $form_state->setRebuild();
merlinofchaos's avatar
merlinofchaos committed
326 327
      $this->view->exposed_data = array();
    }
328 329 330

    $form_state->setRedirect('<current>');
    $form_state->setValues([]);
merlinofchaos's avatar
merlinofchaos committed
331
  }
332

333 334 335
  /**
   * {@inheritdoc}
   */
336 337
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = [];
    if ($this->options['expose_sort_order']) {
      // The sort order query arg is just important in case there is a exposed
      // sort order.
      $has_exposed_sort_handler = FALSE;
      /** @var \Drupal\views\Plugin\views\sort\SortPluginBase $sort_handler */
      foreach ($this->displayHandler->getHandlers('sort') as $sort_handler) {
        if ($sort_handler->isExposed()) {
          $has_exposed_sort_handler = TRUE;
        }
      }

      if ($has_exposed_sort_handler) {
        $contexts[] = 'url.query_args:sort_order';
      }
    }

361 362 363 364 365 366 367 368
    // Merge in cache contexts for all exposed filters to prevent display of
    // cached forms.
    foreach ($this->displayHandler->getHandlers('filter') as $filter_hander) {
      if ($filter_hander->isExposed()) {
        $contexts = Cache::mergeContexts($contexts, $filter_hander->getCacheContexts());
      }
    }

369 370 371
    return $contexts;
  }

372 373 374 375 376 377 378
  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return [];
  }

merlinofchaos's avatar
merlinofchaos committed
379
}