FilterPluginBase.php 55.1 KB
Newer Older
1 2
<?php

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

5 6
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
7
use Drupal\Core\Form\FormHelper;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\Core\Render\Element;
10
use Drupal\Core\Render\Element\Checkboxes;
11
use Drupal\user\RoleInterface;
12
use Drupal\views\Plugin\views\HandlerBase;
13
use Drupal\Component\Utility\Html;
14
use Drupal\views\Plugin\views\display\DisplayPluginBase;
15
use Drupal\views\ViewExecutable;
16

17
/**
18
 * @defgroup views_filter_handlers Views filter handler plugins
19
 * @{
20
 * Plugins that handle views filtering.
21
 *
22
 * Filter handler plugins extend
23
 * \Drupal\views\Plugin\views\filter\FilterPluginBase. They must be annotated
24 25 26 27 28
 * with \Drupal\views\Annotation\ViewsFilter annotation, and they must be in
 * namespace directory Plugin\views\filter.
 *
 * The following items can go into a hook_views_data() implementation in a
 * filter section to affect how the filter handler will behave:
29 30 31
 * - allow empty: If true, the 'IS NULL' and 'IS NOT NULL' operators become
 *   available as standard operators.
 *
32 33 34 35 36 37
 * You can refine the behavior of filters by setting the following Boolean
 * member variables to TRUE in your plugin class:
 * - $alwaysMultiple: Disable the possibility of forcing a single value.
 * - $no_operator: Disable the possibility of using operators.
 * - $always_required: Disable the possibility of allowing an exposed input to
 *   be optional.
38
 *
39 40
 * @ingroup views_plugins
 * @see plugin_api
41 42 43
 */

/**
44
 * Base class for Views filters handler plugins.
45
 */
46
abstract class FilterPluginBase extends HandlerBase implements CacheableDependencyInterface {
47

48 49 50 51
  /**
   * Contains the actual value of the field,either configured in the views ui
   * or entered in the exposed filters.
   */
52
  public $value = NULL;
53 54 55 56

  /**
   * Contains the operator which is used on the query.
   */
57
  public $operator = '=';
58

59
  /**
60
   * Contains the information of the selected item in a grouped filter.
61
   */
62
  public $group_info = NULL;
63

64 65 66 67
  /**
   * @var bool
   * Disable the possibility to force a single value.
   */
68
  protected $alwaysMultiple = FALSE;
69 70 71 72 73

  /**
   * @var bool
   * Disable the possibility to use operators.
   */
74
  public $no_operator = FALSE;
75 76 77 78 79

  /**
   * @var bool
   * Disable the possibility to allow a exposed input to be optional.
   */
80
  public $always_required = FALSE;
81 82

  /**
83 84
   * Overrides \Drupal\views\Plugin\views\HandlerBase::init().
   *
85 86 87 88 89
   * Provide some extra help to get the operator/value easier to use.
   *
   * This likely has to be overridden by filters which are more complex
   * than simple operator/value.
   */
90 91
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
92 93 94

    $this->operator = $this->options['operator'];
    $this->value = $this->options['value'];
95
    $this->group_info = $this->options['group_info']['default_group'];
96

97
    // Set the default value of the operator ID.
98
    if (!empty($options['exposed']) && !empty($options['expose']['operator']) && !isset($options['expose']['operator_id'])) {
99
      $this->options['expose']['operator_id'] = $options['expose']['operator'];
100 101
    }

102
    if ($this->multipleExposedInput()) {
103 104 105 106
      $this->group_info = array_filter($options['group_info']['default_group_multiple']);
      $this->options['expose']['multiple'] = TRUE;
    }

107

108 109 110
    // If there are relationships in the view, allow empty should be true
    // so that we can do IS NULL checks on items. Not all filters respect
    // allow empty, but string and numeric do and that covers enough.
111
    if ($this->view->display_handler->getOption('relationships')) {
112 113 114 115
      $this->definition['allow empty'] = TRUE;
    }
  }

116 117
  protected function defineOptions() {
    $options = parent::defineOptions();
118 119 120 121

    $options['operator'] = array('default' => '=');
    $options['value'] = array('default' => '');
    $options['group'] = array('default' => '1');
122
    $options['exposed'] = array('default' => FALSE);
123 124 125
    $options['expose'] = array(
      'contains' => array(
        'operator_id' => array('default' => FALSE),
126 127 128
        'label' => array('default' => ''),
        'description' => array('default' => ''),
        'use_operator' => array('default' => FALSE),
129 130
        'operator' => array('default' => ''),
        'identifier' => array('default' => ''),
131 132 133
        'required' => array('default' => FALSE),
        'remember' => array('default' => FALSE),
        'multiple' => array('default' => FALSE),
134
        'remember_roles' => array('default' => array(
135
          RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID,
136
        )),
137 138 139
      ),
    );

140 141 142 143 144 145 146 147
    // A group is a combination of a filter, an operator and a value
    // operating like a single filter.
    // Users can choose from a select box which group they want to apply.
    // Views will filter the view according to the defined values.
    // Because it acts as a standard filter, we have to define
    // an identifier and other settings like the widget and the label.
    // This settings are saved in another array to allow users to switch
    // between a normal filter and a group of filters with a single click.
148
    $options['is_grouped'] = array('default' => FALSE);
149 150
    $options['group_info'] = array(
      'contains' => array(
151 152
        'label' => array('default' => ''),
        'description' => array('default' => ''),
153
        'identifier' => array('default' => ''),
154
        'optional' => array('default' => TRUE),
155
        'widget' => array('default' => 'select'),
156
        'multiple' => array('default' => FALSE),
157 158 159 160 161 162 163
        'remember' => array('default' => 0),
        'default_group' => array('default' => 'All'),
        'default_group_multiple' => array('default' => array()),
        'group_items' => array('default' => array()),
      ),
    );

164 165 166 167 168 169
    return $options;
  }

  /**
   * Display the filter on the administrative summary
   */
170
  public function adminSummary() {
171
    return $this->operator . ' ' . $this->value;
172 173 174 175 176
  }

  /**
   * Determine if a filter can be exposed.
   */
177
  public function canExpose() { return TRUE; }
178

179 180 181 182
  /**
   * Determine if a filter can be converted into a group.
   * Only exposed filters with operators available can be converted into groups.
   */
183
  protected function canBuildGroup() {
184
    return $this->isExposed() && (count($this->operatorOptions()) > 0);
185 186 187 188 189
  }

  /**
   * Returns TRUE if the exposed filter works like a grouped filter.
   */
190 191
  public function isAGroup() {
    return $this->isExposed() && !empty($this->options['is_grouped']);
192 193
  }

194 195 196 197 198 199
  /**
   * Provide the basic form which calls through to subforms.
   * If overridden, it is best to call through to the parent,
   * or to at least make sure all of the functions in this form
   * are called.
   */
200
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
201
    parent::buildOptionsForm($form, $form_state);
202 203
    if ($this->canExpose()) {
      $this->showExposeButton($form, $form_state);
204
    }
205
    if ($this->canBuildGroup()) {
206
      $this->showBuildGroupButton($form, $form_state);
207
    }
208 209 210
    $form['clear_markup_start'] = array(
      '#markup' => '<div class="clearfix">',
    );
211
    if ($this->isAGroup()) {
212
      if ($this->canBuildGroup()) {
213 214 215 216
        $form['clear_markup_start'] = array(
          '#markup' => '<div class="clearfix">',
        );
        // Render the build group form.
217
        $this->showBuildGroupForm($form, $form_state);
218 219 220 221 222 223
        $form['clear_markup_end'] = array(
          '#markup' => '</div>',
        );
      }
    }
    else {
224
      // Add the subform from operatorForm().
225
      $this->showOperatorForm($form, $form_state);
226
      // Add the subform from valueForm().
227
      $this->showValueForm($form, $form_state);
228 229 230
      $form['clear_markup_end'] = array(
        '#markup' => '</div>',
      );
231 232 233
      if ($this->canExpose()) {
        // Add the subform from buildExposeForm().
        $this->showExposeForm($form, $form_state);
234
      }
235 236 237 238 239 240
    }
  }

  /**
   * Simple validate handler
   */
241
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
242
    $this->operatorValidate($form, $form_state);
243
    $this->valueValidate($form, $form_state);
244 245
    if (!empty($this->options['exposed']) && !$this->isAGroup()) {
      $this->validateExposeForm($form, $form_state);
246
    }
247
    if ($this->isAGroup()) {
248
      $this->buildGroupValidate($form, $form_state);
249
    }
250 251 252 253 254
  }

  /**
   * Simple submit handler
   */
255
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
256 257 258 259
    // Do not store these values.
    $form_state->unsetValue('expose_button');
    $form_state->unsetValue('group_button');

260
    if (!$this->isAGroup()) {
261
      $this->operatorSubmit($form, $form_state);
262
      $this->valueSubmit($form, $form_state);
263
    }
264
    if (!empty($this->options['exposed'])) {
265
      $this->submitExposeForm($form, $form_state);
266
    }
267
    if ($this->isAGroup()) {
268
      $this->buildGroupSubmit($form, $form_state);
269
    }
270 271 272 273 274
  }

  /**
   * Shortcut to display the operator form.
   */
275
  public function showOperatorForm(&$form, FormStateInterface $form_state) {
276
    $this->operatorForm($form, $form_state);
277 278 279 280 281 282 283 284 285 286
    $form['operator']['#prefix'] = '<div class="views-group-box views-left-30">';
    $form['operator']['#suffix'] = '</div>';
  }

  /**
   * Options form subform for setting the operator.
   *
   * This may be overridden by child classes, and it must
   * define $form['operator'];
   *
287
   * @see buildOptionsForm()
288
   */
289
  protected function operatorForm(&$form, FormStateInterface $form_state) {
290
    $options = $this->operatorOptions();
291 292 293
    if (!empty($options)) {
      $form['operator'] = array(
        '#type' => count($options) < 10 ? 'radios' : 'select',
294
        '#title' => $this->t('Operator'),
295 296 297 298 299 300 301 302
        '#default_value' => $this->operator,
        '#options' => $options,
      );
    }
  }

  /**
   * Provide a list of options for the default operator form.
303
   * Should be overridden by classes that don't override operatorForm
304
   */
305
  public function operatorOptions() { return array(); }
306 307 308 309

  /**
   * Validate the operator form.
   */
310
  protected function operatorValidate($form, FormStateInterface $form_state) { }
311 312 313 314 315

  /**
   * Perform any necessary changes to the form values prior to storage.
   * There is no need for this function to actually store the data.
   */
316
  public function operatorSubmit($form, FormStateInterface $form_state) { }
317 318 319 320

  /**
   * Shortcut to display the value form.
   */
321
  protected function showValueForm(&$form, FormStateInterface $form_state) {
322
    $this->valueForm($form, $form_state);
323 324 325 326 327 328 329 330 331 332 333 334
    if (empty($this->no_operator)) {
      $form['value']['#prefix'] = '<div class="views-group-box views-right-70">' . (isset($form['value']['#prefix']) ? $form['value']['#prefix'] : '');
      $form['value']['#suffix'] = (isset($form['value']['#suffix']) ? $form['value']['#suffix'] : '') . '</div>';
    }
  }

  /**
   * Options form subform for setting options.
   *
   * This should be overridden by all child classes and it must
   * define $form['value']
   *
335
   * @see buildOptionsForm()
336
   */
337 338 339
  protected function valueForm(&$form, FormStateInterface $form_state) {
    $form['value'] = array();
  }
340 341 342 343

  /**
   * Validate the options form.
   */
344
  protected function valueValidate($form, FormStateInterface $form_state) { }
345 346 347 348 349

  /**
   * Perform any necessary changes to the form values prior to storage.
   * There is no need for this function to actually store the data.
   */
350
  protected function valueSubmit($form, FormStateInterface $form_state) { }
351

352 353 354
  /**
   * Shortcut to display the exposed options form.
   */
355
  public function showBuildGroupForm(&$form, FormStateInterface $form_state) {
356 357 358 359
    if (empty($this->options['is_grouped'])) {
      return;
    }

360
    $this->buildExposedFiltersGroupForm($form, $form_state);
361 362

    // When we click the expose button, we add new gadgets to the form but they
363
    // have no data in POST so their defaults get wiped out. This prevents
364 365
    // these defaults from getting wiped out. This setting will only be TRUE
    // during a 2nd pass rerender.
366
    if ($form_state->get('force_build_group_options')) {
367
      foreach (Element::children($form['group_info']) as $id) {
368 369 370 371 372 373 374 375 376 377
        if (isset($form['group_info'][$id]['#default_value']) && !isset($form['group_info'][$id]['#value'])) {
          $form['group_info'][$id]['#value'] = $form['group_info'][$id]['#default_value'];
        }
      }
    }
  }

  /**
   * Shortcut to display the build_group/hide button.
   */
378
  protected function showBuildGroupButton(&$form, FormStateInterface $form_state) {
379 380 381 382 383 384 385 386

    $form['group_button'] = array(
      '#prefix' => '<div class="views-grouped clearfix">',
      '#suffix' => '</div>',
      // Should always come after the description and the relationship.
      '#weight' => -190,
    );

387
    $grouped_description = $this->t('Grouped filters allow a choice between predefined operator|value pairs.');
388 389 390 391 392
    $form['group_button']['radios'] = array(
      '#theme_wrappers' => array('container'),
      '#attributes' => array('class' => array('js-only')),
    );
    $form['group_button']['radios']['radios'] = array(
393
      '#title' => $this->t('Filter type to expose'),
394 395 396
      '#description' => $grouped_description,
      '#type' => 'radios',
      '#options' => array(
397 398
        $this->t('Single filter'),
        $this->t('Grouped filters'),
399 400 401 402 403 404 405 406 407 408
      ),
    );

    if (empty($this->options['is_grouped'])) {
      $form['group_button']['markup'] = array(
        '#markup' => '<div class="description grouped-description">' . $grouped_description . '</div>',
      );
      $form['group_button']['button'] = array(
        '#limit_validation_errors' => array(),
        '#type' => 'submit',
409
        '#value' => $this->t('Grouped filters'),
410
        '#submit' => array(array($this, 'buildGroupForm')),
411 412 413 414 415 416 417
      );
      $form['group_button']['radios']['radios']['#default_value'] = 0;
    }
    else {
      $form['group_button']['button'] = array(
        '#limit_validation_errors' => array(),
        '#type' => 'submit',
418
        '#value' => $this->t('Single filter'),
419
        '#submit' => array(array($this, 'buildGroupForm')),
420 421 422 423
      );
      $form['group_button']['radios']['radios']['#default_value'] = 1;
    }
  }
424 425 426 427

  /**
   * Displays the Build Group form.
   */
428
  public function buildGroupForm($form, FormStateInterface $form_state) {
429 430 431 432 433 434
    $item = &$this->options;
    // flip. If the filter was a group, set back to a standard filter.
    $item['is_grouped'] = empty($item['is_grouped']);

    // If necessary, set new defaults:
    if ($item['is_grouped']) {
435
      $this->buildGroupOptions();
436 437
    }

438 439 440 441 442
    $view = $form_state->get('view');
    $display_id = $form_state->get('display_id');
    $type = $form_state->get('type');
    $id = $form_state->get('id');
    $view->getExecutable()->setHandler($display_id, $type, $id, $item);
443

444
    $view->addFormToStack($form_state->get('form_key'), $display_id, $type, $id, TRUE, TRUE);
445

446 447 448 449
    $view->cacheSet();
    $form_state->set('rerender', TRUE);
    $form_state->setRebuild();
    $form_state->get('force_build_group_options', TRUE);
450 451
  }

452 453 454
  /**
   * Shortcut to display the expose/hide button.
   */
455
  public function showExposeButton(&$form, FormStateInterface $form_state) {
456 457 458 459 460 461 462 463 464 465 466 467 468 469
    $form['expose_button'] = array(
      '#prefix' => '<div class="views-expose clearfix">',
      '#suffix' => '</div>',
      // Should always come after the description and the relationship.
      '#weight' => -200,
    );

    // Add a checkbox for JS users, which will have behavior attached to it
    // so it can replace the button.
    $form['expose_button']['checkbox'] = array(
      '#theme_wrappers' => array('container'),
      '#attributes' => array('class' => array('js-only')),
    );
    $form['expose_button']['checkbox']['checkbox'] = array(
470
      '#title' => $this->t('Expose this filter to visitors, to allow them to change it'),
471 472 473 474 475 476
      '#type' => 'checkbox',
    );

    // Then add the button itself.
    if (empty($this->options['exposed'])) {
      $form['expose_button']['markup'] = array(
477
        '#markup' => '<div class="description exposed-description">' . $this->t('This filter is not exposed. Expose it to allow the users to change it.') . '</div>',
478 479 480 481
      );
      $form['expose_button']['button'] = array(
        '#limit_validation_errors' => array(),
        '#type' => 'submit',
482
        '#value' => $this->t('Expose filter'),
483
        '#submit' => array(array($this, 'displayExposedForm')),
484 485 486 487 488
      );
      $form['expose_button']['checkbox']['checkbox']['#default_value'] = 0;
    }
    else {
      $form['expose_button']['markup'] = array(
489
        '#markup' => '<div class="description exposed-description">' . $this->t('This filter is exposed. If you hide it, users will not be able to change it.') . '</div>',
490 491 492 493
      );
      $form['expose_button']['button'] = array(
        '#limit_validation_errors' => array(),
        '#type' => 'submit',
494
        '#value' => $this->t('Hide filter'),
495
        '#submit' => array(array($this, 'displayExposedForm')),
496 497 498 499 500 501 502 503
      );
      $form['expose_button']['checkbox']['checkbox']['#default_value'] = 1;
    }
  }

  /**
   * Options form subform for exposed filter options.
   *
504
   * @see buildOptionsForm()
505
   */
506
  public function buildExposeForm(&$form, FormStateInterface $form_state) {
507 508
    $form['#theme'] = 'views_ui_expose_filter_form';
    // #flatten will move everything from $form['expose'][$key] to $form[$key]
509 510
    // prior to rendering. That's why the preRender for it needs to run first,
    // so that when the next preRender (the one for fieldsets) runs, it gets
511
    // the flattened data.
512
    array_unshift($form['#pre_render'], array(get_class($this), 'preRenderFlattenData'));
513 514 515 516 517
    $form['expose']['#flatten'] = TRUE;

    if (empty($this->always_required)) {
      $form['expose']['required'] = array(
        '#type' => 'checkbox',
518
        '#title' => $this->t('Required'),
519 520 521 522 523 524 525 526 527 528 529 530
        '#default_value' => $this->options['expose']['required'],
      );
    }
    else {
      $form['expose']['required'] = array(
        '#type' => 'value',
        '#value' => TRUE,
      );
    }
    $form['expose']['label'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['expose']['label'],
531
      '#title' => $this->t('Label'),
532 533 534
      '#size' => 40,
    );

535 536 537
    $form['expose']['description'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['expose']['description'],
538
      '#title' => $this->t('Description'),
539 540 541
      '#size' => 60,
    );

542
    if (!empty($form['operator']['#type'])) {
543
      // Increase the width of the left (operator) column.
544 545 546 547 548 549 550
      $form['operator']['#prefix'] = '<div class="views-group-box views-left-40">';
      $form['operator']['#suffix'] = '</div>';
      $form['value']['#prefix'] = '<div class="views-group-box views-right-60">';
      $form['value']['#suffix'] = '</div>';

      $form['expose']['use_operator'] = array(
        '#type' => 'checkbox',
551 552
        '#title' => $this->t('Expose operator'),
        '#description' => $this->t('Allow the user to choose the operator.'),
553 554 555 556 557
        '#default_value' => !empty($this->options['expose']['use_operator']),
      );
      $form['expose']['operator_id'] = array(
        '#type' => 'textfield',
        '#default_value' => $this->options['expose']['operator_id'],
558
        '#title' => $this->t('Operator identifier'),
559
        '#size' => 40,
560
        '#description' => $this->t('This will appear in the URL after the ? to identify this operator.'),
561 562 563 564
        '#states' => array(
          'visible' => array(
            ':input[name="options[expose][use_operator]"]' => array('checked' => TRUE),
          ),
565 566 567 568 569 570 571 572 573 574
        ),
      );
    }
    else {
      $form['expose']['operator_id'] = array(
        '#type' => 'value',
        '#value' => '',
      );
    }

575
    if (empty($this->alwaysMultiple)) {
576 577
      $form['expose']['multiple'] = array(
        '#type' => 'checkbox',
578 579
        '#title' => $this->t('Allow multiple selections'),
        '#description' => $this->t('Enable to allow users to select multiple items.'),
580 581 582 583 584
        '#default_value' => $this->options['expose']['multiple'],
      );
    }
    $form['expose']['remember'] = array(
      '#type' => 'checkbox',
585 586
      '#title' => $this->t('Remember the last selection'),
      '#description' => $this->t('Enable to remember the last selection made by the user.'),
587 588 589
      '#default_value' => $this->options['expose']['remember'],
    );

590
    $role_options = array_map('\Drupal\Component\Utility\Html::escape', user_role_names());
591 592
    $form['expose']['remember_roles'] = array(
      '#type' => 'checkboxes',
593 594
      '#title' => $this->t('User roles'),
      '#description' => $this->t('Remember exposed selection only for the selected user role(s). If you select no roles, the exposed data will never be stored.'),
595 596 597 598 599 600 601 602 603
      '#default_value' => $this->options['expose']['remember_roles'],
      '#options' => $role_options,
      '#states' => array(
        'invisible' => array(
          ':input[name="options[expose][remember]"]' => array('checked' => FALSE),
        ),
      ),
    );

604 605 606
    $form['expose']['identifier'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['expose']['identifier'],
607
      '#title' => $this->t('Filter identifier'),
608
      '#size' => 40,
609
      '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
610 611 612 613 614 615
    );
  }

  /**
   * Validate the options form.
   */
616
  public function validateExposeForm($form, FormStateInterface $form_state) {
617
    $identifier = $form_state->getValue(array('options', 'expose', 'identifier'));
618
    $this->validateIdentifier($identifier, $form_state, $form['expose']['identifier']);
619 620
  }

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  /**
   * Determines if the given grouped filter entry has a valid value.
   *
   * @param array $group
   *   A group entry as defined by buildGroupForm().
   *
   * @return bool
   */
  protected function hasValidGroupedValue(array $group) {
    $operators = $this->operators();
    if ($operators[$group['operator']]['values'] == 0) {
      // Some filters, such as "is empty," do not require a value to be
      // specified in order to be valid entries.
      return TRUE;
    }
    else {
      if (is_string($group['value'])) {
        return trim($group['value']) != '';
      }
      elseif (is_array($group['value'])) {
        // Some filters allow multiple options to be selected (for example, node
        // types). Ensure at least the minimum number of values is present for
        // this entry to be considered valid.
        $min_values = $operators[$group['operator']]['values'];
        $actual_values = count(array_filter($group['value'], 'static::arrayFilterZero'));
        return $actual_values >= $min_values;
      }
    }
    return FALSE;
  }


653
  /**
654 655
   * Validate the build group options form.
   */
656
  protected function buildGroupValidate($form, FormStateInterface $form_state) {
657 658
    if (!$form_state->isValueEmpty(array('options', 'group_info'))) {
      $identifier = $form_state->getValue(array('options', 'group_info', 'identifier'));
659
      $this->validateIdentifier($identifier, $form_state, $form['group_info']['identifier']);
660 661
    }

662 663
    if ($group_items = $form_state->getValue(array('options', 'group_info', 'group_items'))) {
      foreach ($group_items as $id => $group) {
664
        if (empty($group['remove'])) {
665 666 667 668 669
          $has_valid_value = $this->hasValidGroupedValue($group);
          if ($has_valid_value && $group['title'] == '') {
            $operators = $this->operators();
            if ($operators[$group['operator']]['values'] == 0) {
              $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required for the specified operator.'));
670
            }
671 672
            else {
              $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required if the value for this item is defined.'));
673 674
            }
          }
675 676 677
          if (!$has_valid_value && $group['title'] != '') {
            $form_state->setError($form['group_info']['group_items'][$id]['value'], $this->t('A value is required if the label for this item is defined.'));
          }
678 679 680 681 682
        }
      }
    }
  }

683 684 685 686 687 688 689 690 691 692 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
  /**
   * Validates a filter identifier.
   *
   * Sets the form error if $form_state is passed or a error string if
   * $form_state is not passed.
   *
   * @param string $identifier
   *   The identifier to check.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param array $form_group
   *   The form element to set any errors on.
   *
   * @return string
   */
  protected function validateIdentifier($identifier, FormStateInterface $form_state = NULL, &$form_group = array()) {
    $error = '';
    if (empty($identifier)) {
      $error = $this->t('The identifier is required if the filter is exposed.');
    }
    elseif ($identifier == 'value') {
      $error = $this->t('This identifier is not allowed.');
    }
    elseif (preg_match('/[^a-zA-z0-9_~\.\-]/', $identifier)) {
      $error = $this->t('This identifier has illegal characters.');
    }

    if ($form_state && !$this->view->display_handler->isIdentifierUnique($form_state->get('id'), $identifier)) {
      $error = $this->t('This identifier is used by another handler.');
    }

    if (!empty($form_state) && !empty($error)) {
      $form_state->setError($form_group, $error);
    }
    return $error;
  }

719 720 721
  /**
   * Save new group items, re-enumerates and remove groups marked to delete.
   */
722
  protected function buildGroupSubmit($form, FormStateInterface $form_state) {
723
    $groups = array();
724 725
    $group_items = $form_state->getValue(array('options', 'group_info', 'group_items'));
    uasort($group_items, array('Drupal\Component\Utility\SortArray', 'sortByWeightElement'));
726 727 728 729 730
    // Filter out removed items.

    // Start from 1 to avoid problems with #default_value in the widget.
    $new_id = 1;
    $new_default = 'All';
731
    foreach ($group_items as $id => $group) {
732 733 734 735 736 737
      if (empty($group['remove'])) {
        // Don't store this.
        unset($group['remove']);
        unset($group['weight']);
        $groups[$new_id] = $group;

738
        if ($form_state->getValue(array('options', 'group_info', 'default_group')) == $id) {
739 740 741 742 743 744
          $new_default = $new_id;
        }
      }
      $new_id++;
    }
    if ($new_default != 'All') {
745
      $form_state->setValue(array('options', 'group_info', 'default_group'), $new_default);
746
    }
747 748
    $filter_default_multiple = $form_state->getValue(array('options', 'group_info', 'default_group_multiple'));
    $form_state->setValue(array('options', 'group_info', 'default_group_multiple'), array_filter($filter_default_multiple));
749

750
    $form_state->setValue(array('options', 'group_info', 'group_items'), $groups);
751 752
  }

753 754 755
  /**
   * Provide default options for exposed filters.
   */
756
  public function defaultExposeOptions() {
757 758 759 760 761
    $this->options['expose'] = array(
      'use_operator' => FALSE,
      'operator' => $this->options['id'] . '_op',
      'identifier' => $this->options['id'],
      'label' => $this->definition['title'],
762
      'description' => NULL,
763 764 765 766 767 768
      'remember' => FALSE,
      'multiple' => FALSE,
      'required' => FALSE,
    );
  }

769
  /**
770 771
   * Provide default options for exposed filters.
   */
772
  protected function buildGroupOptions() {
773 774
    $this->options['group_info'] = array(
      'label' => $this->definition['title'],
775
      'description' => NULL,
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
      'identifier' => $this->options['id'],
      'optional' => TRUE,
      'widget' => 'select',
      'multiple' => FALSE,
      'remember' => FALSE,
      'default_group' => 'All',
      'default_group_multiple' => array(),
      'group_items' => array(),
    );
  }

  /**
   * Build a form containing a group of operator | values to apply as a
   * single filter.
   */
791
  public function groupForm(&$form, FormStateInterface $form_state) {
792
    if (!empty($this->options['group_info']['optional']) && !$this->multipleExposedInput()) {
793
      $groups = array('All' => $this->t('- Any -'));
794 795 796
    }
    foreach ($this->options['group_info']['group_items'] as $id => $group) {
      if (!empty($group['title'])) {
797
        $groups[$id] = $id != 'All' ? $this->t($group['title']) : $group['title'];
798 799 800 801 802 803 804
      }
    }

    if (count($groups)) {
      $value = $this->options['group_info']['identifier'];

      $form[$value] = array(
805
        '#title' => $this->options['group_info']['label'],
806 807 808 809 810 811 812 813 814 815 816 817 818 819
        '#type' => $this->options['group_info']['widget'],
        '#default_value' => $this->group_info,
        '#options' => $groups,
      );
      if (!empty($this->options['group_info']['multiple'])) {
        if (count($groups) < 5) {
          $form[$value]['#type'] = 'checkboxes';
        }
        else {
          $form[$value]['#type'] = 'select';
          $form[$value]['#size'] = 5;
          $form[$value]['#multiple'] = TRUE;
        }
        unset($form[$value]['#default_value']);
820 821 822 823
        $user_input = $form_state->getUserInput();
        if (empty($user_input)) {
          $user_input[$value] = $this->group_info;
          $form_state->setUserInput($user_input);
824 825 826 827 828 829 830 831
        }
      }

      $this->options['expose']['label'] = '';
    }
  }


832 833 834 835 836
  /**
   * Render our chunk of the exposed filter form when selecting
   *
   * You can override this if it doesn't do what you expect.
   */
837
  public function buildExposedForm(&$form, FormStateInterface $form_state) {
838 839 840 841 842 843 844
    if (empty($this->options['exposed'])) {
      return;
    }

    // Build the exposed form, when its based on an operator.
    if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id'])) {
      $operator = $this->options['expose']['operator_id'];
845
      $this->operatorForm($form, $form_state);
846 847
      $form[$operator] = $form['operator'];

848
      $this->exposedTranslate($form[$operator], 'operator');
849 850 851 852 853 854 855

      unset($form['operator']);
    }

    // Build the form and set the value based on the identifier.
    if (!empty($this->options['expose']['identifier'])) {
      $value = $this->options['expose']['identifier'];
856
      $this->valueForm($form, $form_state);
857 858 859 860 861 862
      $form[$value] = $form['value'];

      if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
        unset($form[$value]['#title']);
      }

863
      $this->exposedTranslate($form[$value], 'value');
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

      if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
        unset($form[$value]['#default_value']);
      }

      if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
        $form[$value]['#default_value'] = 'All';
      }

      if ($value != 'value') {
        unset($form['value']);
      }
    }
  }

879 880 881 882
  /**
   * Build the form to let users create the group of exposed filters.
   * This form is displayed when users click on button 'Build group'
   */
883
  protected function buildExposedFiltersGroupForm(&$form, FormStateInterface $form_state) {
884 885 886 887 888 889
    if (empty($this->options['exposed']) || empty($this->options['is_grouped'])) {
      return;
    }
    $form['#theme'] = 'views_ui_build_group_filter_form';

    // #flatten will move everything from $form['group_info'][$key] to $form[$key]
890 891
    // prior to rendering. That's why the preRender for it needs to run first,
    // so that when the next preRender (the one for fieldsets) runs, it gets
892
    // the flattened data.
893
    array_unshift($form['#pre_render'], array(get_class($this), 'preRenderFlattenData'));
894 895 896 897 898 899 900 901 902 903 904
    $form['group_info']['#flatten'] = TRUE;

    if (!empty($this->options['group_info']['identifier'])) {
      $identifier = $this->options['group_info']['identifier'];
    }
    else {
      $identifier = 'group_' . $this->options['expose']['identifier'];
    }
    $form['group_info']['identifier'] = array(
      '#type' => 'textfield',
      '#default_value' => $identifier,
905
      '#title' => $this->t('Filter identifier'),
906
      '#size' => 40,
907
      '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
908 909 910 911
    );
    $form['group_info']['label'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['group_info']['label'],
912
      '#title' => $this->t('Label'),
913 914
      '#size' => 40,
    );
915 916 917
    $form['group_info']['description'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['group_info']['description'],
918
      '#title' => $this->t('Description'),
919 920
      '#size' => 60,
    );
921 922
    $form['group_info']['optional'] = array(
      '#type' => 'checkbox',
923 924
      '#title' => $this->t('Optional'),
      '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
925 926 927 928
      '#default_value' => $this->options['group_info']['optional'],
    );
    $form['group_info']['multiple'] = array(
      '#type' => 'checkbox',
929 930
      '#title' => $this->t('Allow multiple selections'),
      '#description' => $this->t('Enable to allow users to select multiple items.'),
931 932 933 934 935
      '#default_value' => $this->options['group_info']['multiple'],
    );
    $form['group_info']['widget'] = array(
      '#type' => 'radios',
      '#default_value' => $this->options['group_info']['widget'],
936
      '#title' => $this->t('Widget type'),
937
      '#options' => array(
938 939
        'radios' => $this->t('Radios'),
        'select' => $this->t('Select'),
940
      ),
941
      '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
942 943 944
    );
    $form['group_info']['remember'] = array(
      '#type' => 'checkbox',
945 946
      '#title' => $this->t('Remember'),
      '#description' => $this->t('Remember the last setting the user gave this filter.'),
947 948 949 950 951 952 953 954 955 956 957 958
      '#default_value' => $this->options['group_info']['remember'],
    );

    if (!empty($this->options['group_info']['identifier'])) {
      $identifier = $this->options['group_info']['identifier'];
    }
    else {
      $identifier = 'group_' . $this->options['expose']['identifier'];
    }
    $form['group_info']['identifier'] = array(
      '#type' => 'textfield',
      '#default_value' => $identifier,
959
      '#title' => $this->t('Filter identifier'),
960
      '#size' => 40,
961
      '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
962 963 964 965
    );
    $form['group_info']['label'] = array(
      '#type' => 'textfield',
      '#default_value' => $this->options['group_info']['label'],
966
      '#title' => $this->t('Label'),
967 968 969 970
      '#size' => 40,
    );
    $form['group_info']['optional'] = array(
      '#type' => 'checkbox',
971 972
      '#title' => $this->t('Optional'),
      '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
973 974 975 976 977
      '#default_value' => $this->options['group_info']['optional'],
    );
    $form['group_info']['widget'] = array(
      '#type' => 'radios',
      '#default_value' => $this->options['group_info']['widget'],
978
      '#title' => $this->t('Widget type'),
979
      '#options' => array(
980 981
        'radios' => $this->t('Radios'),
        'select' => $this->t('Select'),
982
      ),
983
      '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
984 985 986
    );
    $form['group_info']['remember'] = array(
      '#type' => 'checkbox',
987 988
      '#title' => $this->t('Remember'),
      '#description' => $this->t('Remember the last setting the user gave this filter.'),
989 990 991
      '#default_value' => $this->options['group_info']['remember'],
    );

992
    $groups = array('All' => $this->t('- Any -')); // The string '- Any -' will not be rendered see @theme_views_ui_build_group_filter_form
993 994 995 996 997 998 999 1000 1001

    // Provide 3 options to start when we are in a new group.
    if (count($this->options['group_info']['group_items']) == 0) {
      $this->options['group_info']['group_items'] = array_fill(1, 3, array());
    }

    // After the general settings, comes a table with all the existent groups.
    $default_weight = 0;
    foreach ($this->options['group_info']['group_items'] as $item_id => $item) {
1002
      if (!$form_state->isValueEmpty(array('options', 'group_info', 'group_items', $item_id, 'remove'))) {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        continue;
      }
      // Each rows contains three widgets:
      // a) The title, where users define how they identify a pair of operator | value
      // b) The operator
      // c) The value (or values) to use in the filter with the selected operator

      // In each row, we have to display the operator form and the value from
      // $row acts as a fake form to render each widget in a row.
      $row = array();
1013
      $groups[$item_id] = $this->t('Grouping @id', array('@id' => $item_id));
1014
      $this->operatorForm($row, $form_state);
1015 1016 1017 1018
      // Force the operator form to be a select box. Some handlers uses
      // radios and they occupy a lot of space in a table row.
      $row['operator']['#type'] = 'select';
      $row['operator']['#title'] = '';
1019
      $this->valueForm($row, $form_state);
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
      // Fix the dependencies to update value forms when operators changes. This
      // is needed because forms are inside a new form and their IDs changes.
      // Dependencies are used when operator changes from to 'Between',
      // 'Not Between', etc, and two or more widgets are displayed.
      FormHelper::rewriteStatesSelector($row['value'], ':input[name="options[operator]"]', ':input[name="options[group_info][group_items][' . $item_id . '][operator]"]');

      // Set default values.
      $children = Element::children($row['value']);
      if (!empty($children)) {
        foreach ($children as $child) {
          foreach ($row['value'][$child]['#states']['visible'] as $state) {
            if (isset($state[':input[name="options[group_info][group_items][' . $item_id . '][operator]"]'])) {
              $row['value'][$child]['#title'] = '';

              if (!empty($this->options['group_info']['group_items'][$item_id]['value'][$child])) {
                $row['value'][$child]['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'][$child];
              }
              // Exit this loop and process the next child element.
              break;
            }
1041 1042 1043
          }
        }
      }
1044
      else {
1045
        if (isset($this->options['group_info']['group_items'][$item_id]['value']) && $this->options['group_info']['group_items'][$item_id]['value'] != '') {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
          $row['value']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'];
        }
      }

      if (!empty($this->options['group_info']['group_items'][$item_id]['operator'])) {
        $row['operator']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['operator'];
      }

      $default_title = '';
      if (!empty($this->options['group_info']['group_items'][$item_id]['title'])) {
        $default_title = $this->options['group_info']['group_items'][$item_id]['title'];
      }

      // Per item group, we have a title that identifies it.
      $form['group_info']['group_items'][$item_id] = array(
        'title' => array(
1062
          '#title' => $this->t('Label'),
1063
          '#title_display' => 'invisible',
1064 1065 1066 1067 1068 1069
          '#type' => 'textfield',
          '#size' => 20,
          '#default_value' => $default_title,
        ),
        'operator' => $row['operator'],
        'value' => $row['value'],
1070 1071
        // No title is given here, since this input is never displayed. It is
        // only triggered by JavaScript.
1072 1073 1074 1075 1076 1077 1078
        'remove' => array(
          '#type' => 'checkbox',
          '#id' => 'views-removed-' . $item_id,
          '#attributes' => array('class' => array('views-remove-checkbox')),
          '#default_value' => 0,
        ),
        'weight' => array(
1079
          '#title' => $this->t('Weight'),
1080
          '#title_display' => 'invisible',
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
          '#type' => 'weight',
          '#delta' => 10,
          '#default_value' => $default_weight++,
          '#attributes' => array('class' => array('weight')),
        ),
      );
    }
    // From all groups, let chose which is the default.
    $form['group_info']['default_group'] = array(
      '#type' => 'radios',
      '#options' => $groups,
      '#default_value' => $this->options['group_info']['default_group'],
      '#required' => TRUE,
      '#attributes' => array(
        'class' => array('default-radios'),
      )
    );
    // From all groups, let chose which is the default.
    $form['group_info']['default_group_multiple'] = array(
      '#type' => 'checkboxes',
      '#options' => $groups,
      '#default_value' => $this->options['group_info']['default_group_multiple'],
      '#attributes' => array(
        'class' => array('default-checkboxes'),
      )
    );

    $form['group_info']['add_group'] = array(
      '#prefix' => '<div class="views-build-group clear-block">',
      '#suffix' => '</div>',
      '#type' => 'submit',
1112
      '#value' => $this->t('Add another item'),
1113
      '#submit' => array(array($this, 'addGroupForm')),
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    );

    $js = array();
    $js['tableDrag']['views-filter-groups']['weight'][0] = array(
      'target' => 'weight',
      'source' => NULL,
      'relationship' => 'sibling',
      'action' => 'order',
      'hidden' => TRUE,
      'limit' => 0,
    );
1125
    $js_settings = $form_state->get('js_settings');
1126 1127
    if ($js_settings && is_array($js)) {
      $js_settings = array_merge($js_settings, $js);
1128 1129
    }
    else {
1130
      $js_settings = $js;
1131
    }
1132
    $form_state->set('js_settings', $js_settings);
1133 1134
  }

1135 1136 1137
  /**
   * Add a new group to the exposed filter groups.
   */
1138
  public function addGroupForm($form, FormStateInterface $form_state) {
1139 1140 1141 1142 1143
    $item = &$this->options;

    // Add a new row.
    $item['group_info']['group_items'][] = array();

1144 1145 1146 1147 1148
    $view = $form_state->get('view');
    $display_id = $form_state->get('display_id');
    $type = $form_state->get('type');
    $id = $form_state->get('id');
    $view->getExecutable()->setHandler($display_id, $type, $id, $item);
webchick's avatar