ExposedFormPluginBase.php 11.4 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginBase.
6 7
 */

8
namespace Drupal\views\Plugin\views\exposed_form;
9

10
use Drupal\Component\Utility\String;
11 12
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\views\Form\ViewsExposedForm;
14
use Drupal\views\ViewExecutable;
15
use Drupal\views\Plugin\views\display\DisplayPluginBase;
16
use Drupal\views\Plugin\views\PluginBase;
17

18 19 20
/**
 * @defgroup views_exposed_form_plugins Views exposed form plugins
 * @{
21
 * Plugins that handle validation, submission, and rendering of exposed forms.
22
 *
23 24 25 26 27 28 29
 * Exposed forms are used for filters, sorts, and pager settings that are
 * exposed to site visitors. Exposed form plugins handle the rendering,
 * validation, and submission of exposed forms, and may add additional form
 * elements.
 *
 * Exposed form plugins extend
 * \Drupal\views\Plugin\views\exposed_form\ExposedFormPluginBase. They must be
30
 * annotated with \Drupal\views\Annotation\ViewsExposedForm annotation,
31
 * and they must be in namespace directory Plugin\views\exposed_form.
32 33 34
 */

/**
35
 * Base class for Views exposed filter form plugins.
36
 */
37
abstract class ExposedFormPluginBase extends PluginBase {
38

39 40 41
  /**
   * Overrides Drupal\views\Plugin\Plugin::$usesOptions.
   */
42
  protected $usesOptions = TRUE;
43

44 45
  protected function defineOptions() {
    $options = parent::defineOptions();
46
    $options['submit_button'] = array('default' => 'Apply', 'translatable' => TRUE);
47 48 49
    $options['reset_button'] = array('default' => FALSE, 'bool' => TRUE);
    $options['reset_button_label'] = array('default' => 'Reset', 'translatable' => TRUE);
    $options['exposed_sorts_label'] = array('default' => 'Sort by', 'translatable' => TRUE);
50
    $options['expose_sort_order'] = array('default' => TRUE, 'bool' => TRUE);
51 52 53 54 55
    $options['sort_asc_label'] = array('default' => 'Asc', 'translatable' => TRUE);
    $options['sort_desc_label'] = array('default' => 'Desc', 'translatable' => TRUE);
    return $options;
  }

56
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
57
    parent::buildOptionsForm($form, $form_state);
58 59 60 61 62 63 64
    $form['submit_button'] = array(
      '#type' => 'textfield',
      '#title' => t('Submit button text'),
      '#default_value' => $this->options['submit_button'],
      '#required' => TRUE,
    );

65
    $form['reset_button'] = array(
66
      '#type' => 'checkbox',
67
      '#title' => t('Include reset button (resets all applied exposed filters).'),
68 69 70 71 72 73 74 75 76
      '#default_value' => $this->options['reset_button'],
    );

    $form['reset_button_label'] = array(
     '#type' => 'textfield',
      '#title' => t('Reset button label'),
      '#description' => t('Text to display in the reset button of the exposed form.'),
      '#default_value' => $this->options['reset_button_label'],
      '#required' => TRUE,
77 78 79 80
      '#states' => array(
        'invisible' => array(
          'input[name="exposed_form_options[reset_button]"]' => array('checked' => FALSE),
        ),
81 82 83 84 85 86 87 88 89 90
      ),
    );

    $form['exposed_sorts_label'] = array(
      '#type' => 'textfield',
      '#title' => t('Exposed sorts label'),
      '#default_value' => $this->options['exposed_sorts_label'],
      '#required' => TRUE,
    );

91 92
    $form['expose_sort_order'] = array(
      '#type' => 'checkbox',
93 94
      '#title' => t('Allow people to choose the sort order'),
      '#description' => t('If sort order is not exposed, the sort criteria settings for each sort will determine its order.'),
95 96 97
      '#default_value' => $this->options['expose_sort_order'],
    );

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

    $form['sort_desc_label'] = array(
      '#type' => 'textfield',
112
      '#title' => t('Label for descending sort'),
113 114
      '#default_value' => $this->options['sort_desc_label'],
      '#required' => TRUE,
115 116 117 118 119
      '#states' => array(
        'visible' => array(
          'input[name="exposed_form_options[expose_sort_order]"]' => array('checked' => TRUE),
        ),
      ),
120 121 122 123 124 125 126 127 128 129
    );
  }

  /**
   * Render the exposed filter form.
   *
   * This actually does more than that; because it's using FAPI, the form will
   * also assign data to the appropriate handlers for use in building the
   * query.
   */
130
  public function renderExposedForm($block = FALSE) {
131
    // Deal with any exposed filters we may have, before building.
132
    $form_state = new FormState(array(
133
      'view' => &$this->view,
134
      'display' => &$this->view->display_handler->display,
135 136 137 138
      'method' => 'get',
      'rerender' => TRUE,
      'no_redirect' => TRUE,
      'always_process' => TRUE,
139
    ));
140 141 142 143

    // 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.
144
    if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
145 146 147 148 149 150 151 152
      unset($form_state['rerender']);
    }

    if (!empty($this->ajax)) {
      $form_state['ajax'] = TRUE;
    }

    $form_state['exposed_form_plugin'] = $this;
153
    $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
154

155
    if (!$this->view->display_handler->displaysExposed() || (!$block && $this->view->display_handler->getOption('exposed_block'))) {
156
      return array();
157 158
    }
    else {
159
      return $form;
160 161 162
    }
  }

163
  public function query() {
164 165 166 167 168 169 170 171 172
    $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) {
173
          if (!$sort->isExposed()) {
174 175
            $sort->query();
          }
176
          elseif ($key == $sort_by) {
177 178 179
            if (isset($exposed_data['sort_order']) && in_array($exposed_data['sort_order'], array('ASC', 'DESC'))) {
              $sort->options['order'] = $exposed_data['sort_order'];
            }
180
            $sort->setRelationship();
181 182 183 184 185 186 187
            $sort->query();
          }
        }
      }
    }
  }

188
  public function preRender($values) { }
189

190
  public function postRender(&$output) { }
191

192
  public function preExecute() { }
193

194
  public function postExecute() { }
195

196 197 198 199 200 201 202 203
  /**
   * Alters the view exposed form.
   *
   * @param $form
   *   The form build array. Passed by reference.
   * @param $form_state
   *   The form state. Passed by reference.
   */
204
  public function exposedFormAlter(&$form, FormStateInterface $form_state) {
205 206 207 208
    if (!empty($this->options['submit_button'])) {
      $form['actions']['submit']['#value'] = $this->options['submit_button'];
    }

209 210 211
    // Check if there is exposed sorts for this view
    $exposed_sorts = array();
    foreach ($this->view->sort as $id => $handler) {
212
      if ($handler->canExpose() && $handler->isExposed()) {
213
        $exposed_sorts[$id] = String::checkPlain($handler->options['expose']['label']);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      }
    }

    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'],
      );
      if (isset($form_state['input']['sort_by']) && isset($this->view->sort[$form_state['input']['sort_by']])) {
        $default_sort_order = $this->view->sort[$form_state['input']['sort_by']]->options['order'];
229 230
      }
      else {
231 232 233 234 235 236 237 238 239
        $first_sort = reset($this->view->sort);
        $default_sort_order = $first_sort->options['order'];
      }

      if (!isset($form_state['input']['sort_by'])) {
        $keys = array_keys($exposed_sorts);
        $form_state['input']['sort_by'] = array_shift($keys);
      }

240 241 242 243
      if ($this->options['expose_sort_order']) {
        $form['sort_order'] = array(
          '#type' => 'select',
          '#options' => $sort_order,
244
          '#title' => t('Order', array(), array('context' => 'Sort order')),
245 246 247
          '#default_value' => $default_sort_order,
        );
      }
248
      $form['submit']['#weight'] = 10;
249 250 251
    }

    if (!empty($this->options['reset_button'])) {
252
      $form['actions']['reset'] = array(
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        '#value' => $this->options['reset_button_label'],
        '#type' => 'submit',
        '#weight' => 10,
      );

      // Get an array of exposed filters, keyed by identifier option.
      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.
      if (!array_intersect_key($all_exposed, $this->view->exposed_input)) {
268
        $form['actions']['reset']['#access'] = FALSE;
269 270 271
      }
    }

272
    $pager = $this->view->display_handler->getPlugin('pager');
273
    if ($pager) {
274
      $pager->exposedFormAlter($form, $form_state);
275 276 277 278
      $form_state['pager_plugin'] = $pager;
    }
  }

279
  public function exposedFormValidate(&$form, FormStateInterface $form_state) {
280
    if (isset($form_state['pager_plugin'])) {
281
      $form_state['pager_plugin']->exposedFormValidate($form, $form_state);
282 283 284 285
    }
  }

  /**
286 287 288 289 290
   * This function is executed when exposed form is submited.
   *
   * @param $form
   *   Nested array of form elements that comprise the form.
   * @param $form_state
291
   *   The current state of the form.
292 293 294 295
   * @param $exclude
   *   Nested array of keys to exclude of insert into
   *   $view->exposed_raw_input
   */
296
  public function exposedFormSubmit(&$form, FormStateInterface $form_state, &$exclude) {
297
    if (!$form_state->isValueEmpty('op') && $form_state->getValue('op') == $this->options['reset_button_label']) {
298
      $this->resetForm($form, $form_state);
299 300
    }
    if (isset($form_state['pager_plugin'])) {
301
      $form_state['pager_plugin']->exposedFormSubmit($form, $form_state, $exclude);
302 303 304 305
      $exclude[] = 'pager_plugin';
    }
  }

306
  public function resetForm(&$form, FormStateInterface $form_state) {
307 308 309 310 311 312
    // _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.
313
    $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
314

315 316
    if (isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
      unset($_SESSION['views'][$this->view->storage->id()][$display_id]);
317 318 319 320 321 322 323 324 325 326 327
    }

    // Set the form to allow redirect.
    if (empty($this->view->live_preview)) {
      $form_state['no_redirect'] = FALSE;
    }
    else {
      $form_state['rebuild'] = TRUE;
      $this->view->exposed_data = array();
    }

328
    $form_state['redirect'] = current_path();
329
  }
330

331 332 333 334 335
}

/**
 * @}
 */