1<?php 2 3namespace Drupal\views\Plugin\views\filter; 4 5use Drupal\Core\Cache\Cache; 6use Drupal\Core\Cache\CacheableDependencyInterface; 7use Drupal\Core\Form\FormHelper; 8use Drupal\Core\Form\FormStateInterface; 9use Drupal\Core\Render\Element; 10use Drupal\Core\Render\Element\Checkboxes; 11use Drupal\user\RoleInterface; 12use Drupal\views\Plugin\views\HandlerBase; 13use Drupal\Component\Utility\Html; 14use Drupal\views\Plugin\views\display\DisplayPluginBase; 15use 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 * with \Drupal\views\Annotation\ViewsFilter annotation, and they must be in 25 * namespace directory Plugin\views\filter. 26 * 27 * The following items can go into a hook_views_data() implementation in a 28 * filter section to affect how the filter handler will behave: 29 * - allow empty: If true, the 'IS NULL' and 'IS NOT NULL' operators become 30 * available as standard operators. 31 * 32 * You can refine the behavior of filters by setting the following Boolean 33 * member variables to TRUE in your plugin class: 34 * - $alwaysMultiple: Disable the possibility of forcing a single value. 35 * - $no_operator: Disable the possibility of using operators. 36 * - $always_required: Disable the possibility of allowing an exposed input to 37 * be optional. 38 * 39 * @ingroup views_plugins 40 * @see plugin_api 41 */ 42 43/** 44 * Base class for Views filters handler plugins. 45 */ 46abstract class FilterPluginBase extends HandlerBase implements CacheableDependencyInterface { 47 48 /** 49 * Contains the actual value of the field,either configured in the views ui 50 * or entered in the exposed filters. 51 */ 52 public $value = NULL; 53 54 /** 55 * Contains the operator which is used on the query. 56 * 57 * @var string 58 */ 59 public $operator = '='; 60 61 /** 62 * Contains the information of the selected item in a grouped filter. 63 */ 64 public $group_info = NULL; 65 66 /** 67 * @var bool 68 * Disable the possibility to force a single value. 69 */ 70 protected $alwaysMultiple = FALSE; 71 72 /** 73 * @var bool 74 * Disable the possibility to use operators. 75 */ 76 public $no_operator = FALSE; 77 78 /** 79 * @var bool 80 * Disable the possibility to allow an exposed input to be optional. 81 */ 82 public $always_required = FALSE; 83 84 /** 85 * Overrides \Drupal\views\Plugin\views\HandlerBase::init(). 86 * 87 * Provide some extra help to get the operator/value easier to use. 88 * 89 * This likely has to be overridden by filters which are more complex 90 * than simple operator/value. 91 */ 92 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) { 93 parent::init($view, $display, $options); 94 95 $this->operator = $this->options['operator']; 96 $this->value = $this->options['value']; 97 $this->group_info = $this->options['group_info']['default_group']; 98 99 // Set the default value of the operator ID. 100 if (!empty($options['exposed']) && !empty($options['expose']['operator']) && !isset($options['expose']['operator_id'])) { 101 $this->options['expose']['operator_id'] = $options['expose']['operator']; 102 } 103 104 if ($this->multipleExposedInput()) { 105 $this->group_info = array_filter($options['group_info']['default_group_multiple']); 106 $this->options['expose']['multiple'] = TRUE; 107 } 108 109 // If there are relationships in the view, allow empty should be true 110 // so that we can do IS NULL checks on items. Not all filters respect 111 // allow empty, but string and numeric do and that covers enough. 112 if ($this->view->display_handler->getOption('relationships')) { 113 $this->definition['allow empty'] = TRUE; 114 } 115 } 116 117 protected function defineOptions() { 118 $options = parent::defineOptions(); 119 120 $options['operator'] = ['default' => '=']; 121 $options['value'] = ['default' => '']; 122 $options['group'] = ['default' => '1']; 123 $options['exposed'] = ['default' => FALSE]; 124 $options['expose'] = [ 125 'contains' => [ 126 'operator_id' => ['default' => FALSE], 127 'label' => ['default' => ''], 128 'description' => ['default' => ''], 129 'use_operator' => ['default' => FALSE], 130 'operator' => ['default' => ''], 131 'operator_limit_selection' => ['default' => FALSE], 132 'operator_list' => ['default' => []], 133 'identifier' => ['default' => ''], 134 'required' => ['default' => FALSE], 135 'remember' => ['default' => FALSE], 136 'multiple' => ['default' => FALSE], 137 'remember_roles' => [ 138 'default' => [ 139 RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID, 140 ], 141 ], 142 ], 143 ]; 144 145 // A group is a combination of a filter, an operator and a value 146 // operating like a single filter. 147 // Users can choose from a select box which group they want to apply. 148 // Views will filter the view according to the defined values. 149 // Because it acts as a standard filter, we have to define 150 // an identifier and other settings like the widget and the label. 151 // This settings are saved in another array to allow users to switch 152 // between a normal filter and a group of filters with a single click. 153 $options['is_grouped'] = ['default' => FALSE]; 154 $options['group_info'] = [ 155 'contains' => [ 156 'label' => ['default' => ''], 157 'description' => ['default' => ''], 158 'identifier' => ['default' => ''], 159 'optional' => ['default' => TRUE], 160 'widget' => ['default' => 'select'], 161 'multiple' => ['default' => FALSE], 162 'remember' => ['default' => 0], 163 'default_group' => ['default' => 'All'], 164 'default_group_multiple' => ['default' => []], 165 'group_items' => ['default' => []], 166 ], 167 ]; 168 169 return $options; 170 } 171 172 /** 173 * Display the filter on the administrative summary. 174 */ 175 public function adminSummary() { 176 return $this->operator . ' ' . $this->value; 177 } 178 179 /** 180 * Determine if a filter can be exposed. 181 */ 182 public function canExpose() { 183 return TRUE; 184 } 185 186 /** 187 * Determine if a filter can be converted into a group. 188 * Only exposed filters with operators available can be converted into groups. 189 */ 190 protected function canBuildGroup() { 191 return $this->isExposed() && (count($this->operatorOptions()) > 0); 192 } 193 194 /** 195 * Returns TRUE if the exposed filter works like a grouped filter. 196 */ 197 public function isAGroup() { 198 return $this->isExposed() && !empty($this->options['is_grouped']); 199 } 200 201 /** 202 * Provide the basic form which calls through to subforms. 203 * If overridden, it is best to call through to the parent, 204 * or to at least make sure all of the functions in this form 205 * are called. 206 */ 207 public function buildOptionsForm(&$form, FormStateInterface $form_state) { 208 parent::buildOptionsForm($form, $form_state); 209 if ($this->canExpose()) { 210 $this->showExposeButton($form, $form_state); 211 } 212 if ($this->canBuildGroup()) { 213 $this->showBuildGroupButton($form, $form_state); 214 } 215 $form['clear_markup_start'] = [ 216 '#markup' => '<div class="clearfix">', 217 ]; 218 if ($this->isAGroup()) { 219 if ($this->canBuildGroup()) { 220 $form['clear_markup_start'] = [ 221 '#markup' => '<div class="clearfix">', 222 ]; 223 // Render the build group form. 224 $this->showBuildGroupForm($form, $form_state); 225 $form['clear_markup_end'] = [ 226 '#markup' => '</div>', 227 ]; 228 } 229 } 230 else { 231 // Add the subform from operatorForm(). 232 $this->showOperatorForm($form, $form_state); 233 // Add the subform from valueForm(). 234 $this->showValueForm($form, $form_state); 235 $form['clear_markup_end'] = [ 236 '#markup' => '</div>', 237 ]; 238 if ($this->canExpose()) { 239 // Add the subform from buildExposeForm(). 240 $this->showExposeForm($form, $form_state); 241 } 242 } 243 } 244 245 /** 246 * Simple validate handler. 247 */ 248 public function validateOptionsForm(&$form, FormStateInterface $form_state) { 249 $this->operatorValidate($form, $form_state); 250 $this->valueValidate($form, $form_state); 251 if (!empty($this->options['exposed']) && !$this->isAGroup()) { 252 $this->validateExposeForm($form, $form_state); 253 } 254 if ($this->isAGroup()) { 255 $this->buildGroupValidate($form, $form_state); 256 } 257 } 258 259 /** 260 * Simple submit handler. 261 */ 262 public function submitOptionsForm(&$form, FormStateInterface $form_state) { 263 // Do not store these values. 264 $form_state->unsetValue('expose_button'); 265 $form_state->unsetValue('group_button'); 266 267 if (!$this->isAGroup()) { 268 $this->operatorSubmit($form, $form_state); 269 $this->valueSubmit($form, $form_state); 270 } 271 if (!empty($this->options['exposed'])) { 272 $this->submitExposeForm($form, $form_state); 273 } 274 if ($this->isAGroup()) { 275 $this->buildGroupSubmit($form, $form_state); 276 } 277 } 278 279 /** 280 * Shortcut to display the operator form. 281 */ 282 public function showOperatorForm(&$form, FormStateInterface $form_state) { 283 $this->operatorForm($form, $form_state); 284 $form['operator']['#prefix'] = '<div class="views-group-box views-left-30">'; 285 $form['operator']['#suffix'] = '</div>'; 286 } 287 288 /** 289 * Options form subform for setting the operator. 290 * 291 * This may be overridden by child classes, and it must 292 * define $form['operator']; 293 * 294 * @see buildOptionsForm() 295 */ 296 protected function operatorForm(&$form, FormStateInterface $form_state) { 297 $options = $this->operatorOptions(); 298 if (!empty($options)) { 299 $form['operator'] = [ 300 '#type' => count($options) < 10 ? 'radios' : 'select', 301 '#title' => $this->t('Operator'), 302 '#default_value' => $this->operator, 303 '#options' => $options, 304 ]; 305 } 306 } 307 308 /** 309 * Provide a list of options for the default operator form. 310 * 311 * Should be overridden by classes that don't override operatorForm. 312 */ 313 public function operatorOptions() { 314 return []; 315 } 316 317 /** 318 * Validate the operator form. 319 */ 320 protected function operatorValidate($form, FormStateInterface $form_state) {} 321 322 /** 323 * Perform any necessary changes to the form values prior to storage. 324 * 325 * There is no need for this function to actually store the data. 326 */ 327 public function operatorSubmit($form, FormStateInterface $form_state) {} 328 329 /** 330 * Shortcut to display the value form. 331 */ 332 protected function showValueForm(&$form, FormStateInterface $form_state) { 333 $this->valueForm($form, $form_state); 334 if (empty($this->no_operator)) { 335 $form['value']['#prefix'] = '<div class="views-group-box views-right-70">' . (isset($form['value']['#prefix']) ? $form['value']['#prefix'] : ''); 336 $form['value']['#suffix'] = (isset($form['value']['#suffix']) ? $form['value']['#suffix'] : '') . '</div>'; 337 } 338 } 339 340 /** 341 * Options form subform for setting options. 342 * 343 * This should be overridden by all child classes and it must 344 * define $form['value'] 345 * 346 * @see buildOptionsForm() 347 */ 348 protected function valueForm(&$form, FormStateInterface $form_state) { 349 $form['value'] = []; 350 } 351 352 /** 353 * Validate the options form. 354 */ 355 protected function valueValidate($form, FormStateInterface $form_state) {} 356 357 /** 358 * Perform any necessary changes to the form values prior to storage. 359 * 360 * There is no need for this function to actually store the data. 361 */ 362 protected function valueSubmit($form, FormStateInterface $form_state) {} 363 364 /** 365 * Shortcut to display the exposed options form. 366 */ 367 public function showBuildGroupForm(&$form, FormStateInterface $form_state) { 368 if (empty($this->options['is_grouped'])) { 369 return; 370 } 371 372 $this->buildExposedFiltersGroupForm($form, $form_state); 373 374 // When we click the expose button, we add new gadgets to the form but they 375 // have no data in POST so their defaults get wiped out. This prevents 376 // these defaults from getting wiped out. This setting will only be TRUE 377 // during a 2nd pass rerender. 378 if ($form_state->get('force_build_group_options')) { 379 foreach (Element::children($form['group_info']) as $id) { 380 if (isset($form['group_info'][$id]['#default_value']) && !isset($form['group_info'][$id]['#value'])) { 381 $form['group_info'][$id]['#value'] = $form['group_info'][$id]['#default_value']; 382 } 383 } 384 } 385 } 386 387 /** 388 * Shortcut to display the build_group/hide button. 389 */ 390 protected function showBuildGroupButton(&$form, FormStateInterface $form_state) { 391 392 $form['group_button'] = [ 393 '#prefix' => '<div class="views-grouped clearfix">', 394 '#suffix' => '</div>', 395 // Should always come after the description and the relationship. 396 '#weight' => -190, 397 ]; 398 399 $grouped_description = $this->t('Grouped filters allow a choice between predefined operator|value pairs.'); 400 $form['group_button']['radios'] = [ 401 '#theme_wrappers' => ['container'], 402 '#attributes' => ['class' => ['js-only']], 403 ]; 404 $form['group_button']['radios']['radios'] = [ 405 '#title' => $this->t('Filter type to expose'), 406 '#description' => $grouped_description, 407 '#type' => 'radios', 408 '#options' => [ 409 $this->t('Single filter'), 410 $this->t('Grouped filters'), 411 ], 412 ]; 413 414 if (empty($this->options['is_grouped'])) { 415 $form['group_button']['markup'] = [ 416 '#markup' => '<div class="description grouped-description">' . $grouped_description . '</div>', 417 ]; 418 $form['group_button']['button'] = [ 419 '#limit_validation_errors' => [], 420 '#type' => 'submit', 421 '#value' => $this->t('Grouped filters'), 422 '#submit' => [[$this, 'buildGroupForm']], 423 ]; 424 $form['group_button']['radios']['radios']['#default_value'] = 0; 425 } 426 else { 427 $form['group_button']['button'] = [ 428 '#limit_validation_errors' => [], 429 '#type' => 'submit', 430 '#value' => $this->t('Single filter'), 431 '#submit' => [[$this, 'buildGroupForm']], 432 ]; 433 $form['group_button']['radios']['radios']['#default_value'] = 1; 434 } 435 } 436 437 /** 438 * Displays the Build Group form. 439 */ 440 public function buildGroupForm($form, FormStateInterface $form_state) { 441 $item = &$this->options; 442 // flip. If the filter was a group, set back to a standard filter. 443 $item['is_grouped'] = empty($item['is_grouped']); 444 445 // If necessary, set new defaults: 446 if ($item['is_grouped']) { 447 $this->buildGroupOptions(); 448 } 449 450 $view = $form_state->get('view'); 451 $display_id = $form_state->get('display_id'); 452 $type = $form_state->get('type'); 453 $id = $form_state->get('id'); 454 $view->getExecutable()->setHandler($display_id, $type, $id, $item); 455 456 $view->addFormToStack($form_state->get('form_key'), $display_id, $type, $id, TRUE, TRUE); 457 458 $view->cacheSet(); 459 $form_state->set('rerender', TRUE); 460 $form_state->setRebuild(); 461 $form_state->get('force_build_group_options', TRUE); 462 } 463 464 /** 465 * Shortcut to display the expose/hide button. 466 */ 467 public function showExposeButton(&$form, FormStateInterface $form_state) { 468 $form['expose_button'] = [ 469 '#prefix' => '<div class="views-expose clearfix">', 470 '#suffix' => '</div>', 471 // Should always come after the description and the relationship. 472 '#weight' => -200, 473 ]; 474 475 // Add a checkbox for JS users, which will have behavior attached to it 476 // so it can replace the button. 477 $form['expose_button']['checkbox'] = [ 478 '#theme_wrappers' => ['container'], 479 '#attributes' => ['class' => ['js-only']], 480 ]; 481 $form['expose_button']['checkbox']['checkbox'] = [ 482 '#title' => $this->t('Expose this filter to visitors, to allow them to change it'), 483 '#type' => 'checkbox', 484 ]; 485 486 // Then add the button itself. 487 if (empty($this->options['exposed'])) { 488 $form['expose_button']['markup'] = [ 489 '#markup' => '<div class="description exposed-description">' . $this->t('This filter is not exposed. Expose it to allow the users to change it.') . '</div>', 490 ]; 491 $form['expose_button']['button'] = [ 492 '#limit_validation_errors' => [], 493 '#type' => 'submit', 494 '#value' => $this->t('Expose filter'), 495 '#submit' => [[$this, 'displayExposedForm']], 496 ]; 497 $form['expose_button']['checkbox']['checkbox']['#default_value'] = 0; 498 } 499 else { 500 $form['expose_button']['markup'] = [ 501 '#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>', 502 ]; 503 $form['expose_button']['button'] = [ 504 '#limit_validation_errors' => [], 505 '#type' => 'submit', 506 '#value' => $this->t('Hide filter'), 507 '#submit' => [[$this, 'displayExposedForm']], 508 ]; 509 $form['expose_button']['checkbox']['checkbox']['#default_value'] = 1; 510 } 511 } 512 513 /** 514 * Options form subform for exposed filter options. 515 * 516 * @see buildOptionsForm() 517 */ 518 public function buildExposeForm(&$form, FormStateInterface $form_state) { 519 $form['#theme'] = 'views_ui_expose_filter_form'; 520 // #flatten will move everything from $form['expose'][$key] to $form[$key] 521 // prior to rendering. That's why the preRender for it needs to run first, 522 // so that when the next preRender (the one for fieldsets) runs, it gets 523 // the flattened data. 524 array_unshift($form['#pre_render'], [static::class, 'preRenderFlattenData']); 525 $form['expose']['#flatten'] = TRUE; 526 527 if (empty($this->always_required)) { 528 $form['expose']['required'] = [ 529 '#type' => 'checkbox', 530 '#title' => $this->t('Required'), 531 '#default_value' => $this->options['expose']['required'], 532 ]; 533 } 534 else { 535 $form['expose']['required'] = [ 536 '#type' => 'value', 537 '#value' => TRUE, 538 ]; 539 } 540 $form['expose']['label'] = [ 541 '#type' => 'textfield', 542 '#default_value' => $this->options['expose']['label'], 543 '#title' => $this->t('Label'), 544 '#size' => 40, 545 ]; 546 547 $form['expose']['description'] = [ 548 '#type' => 'textfield', 549 '#default_value' => $this->options['expose']['description'], 550 '#title' => $this->t('Description'), 551 '#size' => 60, 552 ]; 553 554 if (!empty($form['operator']['#type'])) { 555 // Increase the width of the left (operator) column. 556 $form['operator']['#prefix'] = '<div class="views-group-box views-left-40">'; 557 $form['operator']['#suffix'] = '</div>'; 558 $form['value']['#prefix'] = '<div class="views-group-box views-right-60">'; 559 $form['value']['#suffix'] = '</div>'; 560 561 $form['expose']['use_operator'] = [ 562 '#type' => 'checkbox', 563 '#title' => $this->t('Expose operator'), 564 '#description' => $this->t('Allow the user to choose the operator.'), 565 '#default_value' => !empty($this->options['expose']['use_operator']), 566 ]; 567 568 $operators = $this->operatorOptions(); 569 if (!empty($operators) && count($operators) > 1) { 570 $form['expose']['operator_limit_selection'] = [ 571 '#type' => 'checkbox', 572 '#title' => $this->t('Limit the available operators'), 573 '#description' => $this->t('Limit the available operators to be shown on the exposed filter.'), 574 '#default_value' => !empty($this->options['expose']['operator_limit_selection']), 575 '#states' => [ 576 'visible' => [ 577 ':input[name="options[expose][use_operator]"]' => ['checked' => TRUE], 578 ], 579 ], 580 ]; 581 $form['expose']['operator_list'] = [ 582 '#type' => 'select', 583 '#title' => $this->t('Restrict operators to'), 584 '#default_value' => $this->options['expose']['operator_list'], 585 '#options' => $operators, 586 '#multiple' => TRUE, 587 '#description' => $this->t('Selecting none will make all of them available.'), 588 '#states' => [ 589 'visible' => [ 590 ':input[name="options[expose][operator_limit_selection]"]' => ['checked' => TRUE], 591 ':input[name="options[expose][use_operator]"]' => ['checked' => TRUE], 592 ], 593 ], 594 ]; 595 } 596 597 $form['expose']['operator_id'] = [ 598 '#type' => 'textfield', 599 '#default_value' => $this->options['expose']['operator_id'], 600 '#title' => $this->t('Operator identifier'), 601 '#size' => 40, 602 '#description' => $this->t('This will appear in the URL after the ? to identify this operator.'), 603 '#states' => [ 604 'visible' => [ 605 ':input[name="options[expose][use_operator]"]' => ['checked' => TRUE], 606 ], 607 ], 608 ]; 609 } 610 else { 611 $form['expose']['operator_id'] = [ 612 '#type' => 'value', 613 '#value' => '', 614 ]; 615 } 616 617 if (empty($this->alwaysMultiple)) { 618 $form['expose']['multiple'] = [ 619 '#type' => 'checkbox', 620 '#title' => $this->t('Allow multiple selections'), 621 '#description' => $this->t('Enable to allow users to select multiple items.'), 622 '#default_value' => $this->options['expose']['multiple'], 623 ]; 624 } 625 $form['expose']['remember'] = [ 626 '#type' => 'checkbox', 627 '#title' => $this->t('Remember the last selection'), 628 '#description' => $this->t('Enable to remember the last selection made by the user.'), 629 '#default_value' => $this->options['expose']['remember'], 630 ]; 631 632 $role_options = array_map('\Drupal\Component\Utility\Html::escape', user_role_names()); 633 $form['expose']['remember_roles'] = [ 634 '#type' => 'checkboxes', 635 '#title' => $this->t('User roles'), 636 '#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.'), 637 '#default_value' => $this->options['expose']['remember_roles'], 638 '#options' => $role_options, 639 '#states' => [ 640 'invisible' => [ 641 ':input[name="options[expose][remember]"]' => ['checked' => FALSE], 642 ], 643 ], 644 ]; 645 646 $form['expose']['identifier'] = [ 647 '#type' => 'textfield', 648 '#default_value' => $this->options['expose']['identifier'], 649 '#title' => $this->t('Filter identifier'), 650 '#size' => 40, 651 '#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.'), 652 ]; 653 } 654 655 /** 656 * {@inheritdoc} 657 */ 658 public static function trustedCallbacks() { 659 $callbacks = parent::trustedCallbacks(); 660 $callbacks[] = 'preRenderFlattenData'; 661 return $callbacks; 662 } 663 664 /** 665 * Validate the options form. 666 */ 667 public function validateExposeForm($form, FormStateInterface $form_state) { 668 $identifier = $form_state->getValue(['options', 'expose', 'identifier']); 669 $this->validateIdentifier($identifier, $form_state, $form['expose']['identifier']); 670 671 $limit_operators = $form_state->getValue(['options', 'expose', 'operator_limit_selection']); 672 $operators_selected = $form_state->getValue(['options', 'expose', 'operator_list']); 673 $selected_operator = $form_state->getValue(['options', 'operator']); 674 if ($limit_operators && !in_array($selected_operator, $operators_selected, TRUE)) { 675 $form_state->setError( 676 $form['expose']['operator_list'], 677 $this->t('You selected the "@operator" operator as the default value but is not included in the list of limited operators.', ['@operator' => $this->operatorOptions()[$selected_operator]])); 678 } 679 } 680 681 /** 682 * Determines if the given grouped filter entry has a valid value. 683 * 684 * @param array $group 685 * A group entry as defined by buildGroupForm(). 686 * 687 * @return bool 688 */ 689 protected function hasValidGroupedValue(array $group) { 690 $operators = $this->operators(); 691 if ($operators[$group['operator']]['values'] == 0) { 692 // Some filters, such as "is empty," do not require a value to be 693 // specified in order to be valid entries. 694 return TRUE; 695 } 696 else { 697 if (is_string($group['value'])) { 698 return trim($group['value']) != ''; 699 } 700 elseif (is_array($group['value'])) { 701 // Some filters allow multiple options to be selected (for example, node 702 // types). Ensure at least the minimum number of values is present for 703 // this entry to be considered valid. 704 $min_values = $operators[$group['operator']]['values']; 705 $actual_values = count(array_filter($group['value'], 'static::arrayFilterZero')); 706 return $actual_values >= $min_values; 707 } 708 } 709 return FALSE; 710 } 711 712 /** 713 * Validate the build group options form. 714 */ 715 protected function buildGroupValidate($form, FormStateInterface $form_state) { 716 if (!$form_state->isValueEmpty(['options', 'group_info'])) { 717 $identifier = $form_state->getValue(['options', 'group_info', 'identifier']); 718 $this->validateIdentifier($identifier, $form_state, $form['group_info']['identifier']); 719 } 720 721 if ($group_items = $form_state->getValue(['options', 'group_info', 'group_items'])) { 722 foreach ($group_items as $id => $group) { 723 if (empty($group['remove'])) { 724 $has_valid_value = $this->hasValidGroupedValue($group); 725 if ($has_valid_value && $group['title'] == '') { 726 $operators = $this->operators(); 727 if ($operators[$group['operator']]['values'] == 0) { 728 $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required for the specified operator.')); 729 } 730 else { 731 $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required if the value for this item is defined.')); 732 } 733 } 734 if (!$has_valid_value && $group['title'] != '') { 735 $form_state->setError($form['group_info']['group_items'][$id]['value'], $this->t('A value is required if the label for this item is defined.')); 736 } 737 } 738 } 739 } 740 } 741 742 /** 743 * Validates a filter identifier. 744 * 745 * Sets the form error if $form_state is passed or an error string if 746 * $form_state is not passed. 747 * 748 * @param string $identifier 749 * The identifier to check. 750 * @param \Drupal\Core\Form\FormStateInterface $form_state 751 * @param array $form_group 752 * The form element to set any errors on. 753 * 754 * @return string 755 */ 756 protected function validateIdentifier($identifier, FormStateInterface $form_state = NULL, &$form_group = []) { 757 $error = ''; 758 if (empty($identifier)) { 759 $error = $this->t('The identifier is required if the filter is exposed.'); 760 } 761 elseif ($identifier == 'value') { 762 $error = $this->t('This identifier is not allowed.'); 763 } 764 elseif (preg_match('/[^a-zA-Z0-9_~\.\-]+/', $identifier)) { 765 $error = $this->t('This identifier has illegal characters.'); 766 } 767 768 if ($form_state && !$this->view->display_handler->isIdentifierUnique($form_state->get('id'), $identifier)) { 769 $error = $this->t('This identifier is used by another handler.'); 770 } 771 772 if (!empty($form_state) && !empty($error)) { 773 $form_state->setError($form_group, $error); 774 } 775 return $error; 776 } 777 778 /** 779 * Save new group items, re-enumerates and remove groups marked to delete. 780 */ 781 protected function buildGroupSubmit($form, FormStateInterface $form_state) { 782 $groups = []; 783 $group_items = $form_state->getValue(['options', 'group_info', 'group_items']); 784 uasort($group_items, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']); 785 // Filter out removed items. 786 787 // Start from 1 to avoid problems with #default_value in the widget. 788 $new_id = 1; 789 $new_default = 'All'; 790 foreach ($group_items as $id => $group) { 791 if (empty($group['remove'])) { 792 // Don't store this. 793 unset($group['remove']); 794 unset($group['weight']); 795 $groups[$new_id] = $group; 796 797 if ($form_state->getValue(['options', 'group_info', 'default_group']) == $id) { 798 $new_default = $new_id; 799 } 800 } 801 $new_id++; 802 } 803 if ($new_default != 'All') { 804 $form_state->setValue(['options', 'group_info', 'default_group'], $new_default); 805 } 806 $filter_default_multiple = $form_state->getValue(['options', 'group_info', 'default_group_multiple']); 807 $form_state->setValue(['options', 'group_info', 'default_group_multiple'], array_filter($filter_default_multiple)); 808 809 $form_state->setValue(['options', 'group_info', 'group_items'], $groups); 810 } 811 812 /** 813 * Provide default options for exposed filters. 814 */ 815 public function defaultExposeOptions() { 816 $this->options['expose'] = [ 817 'use_operator' => FALSE, 818 'operator' => $this->options['id'] . '_op', 819 'operator_limit_selection' => FALSE, 820 'operator_list' => [], 821 'identifier' => $this->options['id'], 822 'label' => $this->definition['title'], 823 'description' => NULL, 824 'remember' => FALSE, 825 'multiple' => FALSE, 826 'required' => FALSE, 827 ]; 828 } 829 830 /** 831 * Provide default options for exposed filters. 832 */ 833 protected function buildGroupOptions() { 834 $this->options['group_info'] = [ 835 'label' => $this->definition['title'], 836 'description' => NULL, 837 'identifier' => $this->options['id'], 838 'optional' => TRUE, 839 'widget' => 'select', 840 'multiple' => FALSE, 841 'remember' => FALSE, 842 'default_group' => 'All', 843 'default_group_multiple' => [], 844 'group_items' => [], 845 ]; 846 } 847 848 /** 849 * Build a form containing a group of operator | values to apply as a 850 * single filter. 851 */ 852 public function groupForm(&$form, FormStateInterface $form_state) { 853 if (!empty($this->options['group_info']['optional']) && !$this->multipleExposedInput()) { 854 $groups = ['All' => $this->t('- Any -')]; 855 } 856 foreach ($this->options['group_info']['group_items'] as $id => $group) { 857 if (!empty($group['title'])) { 858 $groups[$id] = $id != 'All' ? $this->t($group['title']) : $group['title']; 859 } 860 } 861 862 if (count($groups)) { 863 $value = $this->options['group_info']['identifier']; 864 865 $form[$value] = [ 866 '#title' => $this->options['group_info']['label'], 867 '#type' => $this->options['group_info']['widget'], 868 '#default_value' => $this->group_info, 869 '#options' => $groups, 870 ]; 871 if (!empty($this->options['group_info']['multiple'])) { 872 if (count($groups) < 5) { 873 $form[$value]['#type'] = 'checkboxes'; 874 } 875 else { 876 $form[$value]['#type'] = 'select'; 877 $form[$value]['#size'] = 5; 878 $form[$value]['#multiple'] = TRUE; 879 } 880 unset($form[$value]['#default_value']); 881 $user_input = $form_state->getUserInput(); 882 if (empty($user_input)) { 883 $user_input[$value] = $this->group_info; 884 $form_state->setUserInput($user_input); 885 } 886 } 887 888 $this->options['expose']['label'] = ''; 889 } 890 } 891 892 /** 893 * Render our chunk of the exposed filter form when selecting. 894 * 895 * You can override this if it doesn't do what you expect. 896 */ 897 public function buildExposedForm(&$form, FormStateInterface $form_state) { 898 if (empty($this->options['exposed'])) { 899 return; 900 } 901 902 // Build the exposed form, when its based on an operator. 903 if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id'])) { 904 $operator = $this->options['expose']['operator_id']; 905 $this->operatorForm($form, $form_state); 906 907 // Limit the exposed operators if needed. 908 if (!empty($this->options['expose']['operator_limit_selection']) && 909 !empty($this->options['expose']['operator_list'])) { 910 911 $options = $this->operatorOptions(); 912 $operator_list = $this->options['expose']['operator_list']; 913 $form['operator']['#options'] = array_intersect_key($options, $operator_list); 914 } 915 $form[$operator] = $form['operator']; 916 917 $this->exposedTranslate($form[$operator], 'operator'); 918 919 unset($form['operator']); 920 921 // When the operator and value forms are both in play, enclose them within 922 // a wrapper. 923 if (!empty($this->options['expose']['identifier'])) { 924 $wrapper = $this->options['expose']['identifier'] . '_wrapper'; 925 $this->buildValueWrapper($form, $wrapper); 926 $form[$operator]['#title_display'] = 'invisible'; 927 928 $form[$wrapper][$operator] = $form[$operator]; 929 unset($form[$operator]); 930 } 931 } 932 933 // Build the form and set the value based on the identifier. 934 if (!empty($this->options['expose']['identifier'])) { 935 $value = $this->options['expose']['identifier']; 936 $this->valueForm($form, $form_state); 937 $form[$value] = $form['value']; 938 939 if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') { 940 unset($form[$value]['#title']); 941 } 942 943 $this->exposedTranslate($form[$value], 'value'); 944 945 if ($value != 'value') { 946 unset($form['value']); 947 } 948 949 // When the operator and value forms are both in play, enclose them within 950 // a wrapper, for usability. Also wrap if the value form is comprised of 951 // multiple elements. 952 if ((!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id'])) || count(Element::children($form[$value]))) { 953 $wrapper = $value . '_wrapper'; 954 $this->buildValueWrapper($form, $wrapper); 955 $form[$wrapper][$value] = $form[$value]; 956 unset($form[$value]); 957 } 958 } 959 } 960 961 /** 962 * Builds wrapper for value and operator forms. 963 * 964 * @param array $form 965 * The form. 966 * @param string $wrapper_identifier 967 * The key to use for the wrapper element. 968 */ 969 protected function buildValueWrapper(&$form, $wrapper_identifier) { 970 // If both the field and the operator are exposed, this will end up being 971 // called twice. We don't want to wipe out what's already there, so if it 972 // exists already, do nothing. 973 if (!isset($form[$wrapper_identifier])) { 974 $form[$wrapper_identifier] = [ 975 '#type' => 'fieldset', 976 ]; 977 978 $exposed_info = $this->exposedInfo(); 979 if (!empty($exposed_info['label'])) { 980 $form[$wrapper_identifier]['#title'] = $exposed_info['label']; 981 } 982 if (!empty($exposed_info['description'])) { 983 $form[$wrapper_identifier]['#description'] = $exposed_info['description']; 984 } 985 } 986 } 987 988 /** 989 * Build the form to let users create the group of exposed filters. 990 * 991 * This form is displayed when users click on button 'Build group'. 992 */ 993 protected function buildExposedFiltersGroupForm(&$form, FormStateInterface $form_state) { 994 if (empty($this->options['exposed']) || empty($this->options['is_grouped'])) { 995 return; 996 } 997 $form['#theme'] = 'views_ui_build_group_filter_form'; 998 999 // #flatten will move everything from $form['group_info'][$key] to $form[$key] 1000 // prior to rendering. That's why the preRender for it needs to run first, 1001 // so that when the next preRender (the one for fieldsets) runs, it gets 1002 // the flattened data. 1003 array_unshift($form['#pre_render'], [static::class, 'preRenderFlattenData']); 1004 $form['group_info']['#flatten'] = TRUE; 1005 1006 if (!empty($this->options['group_info']['identifier'])) { 1007 $identifier = $this->options['group_info']['identifier']; 1008 } 1009 else { 1010 $identifier = 'group_' . $this->options['expose']['identifier']; 1011 } 1012 $form['group_info']['identifier'] = [ 1013 '#type' => 'textfield', 1014 '#default_value' => $identifier, 1015 '#title' => $this->t('Filter identifier'), 1016 '#size' => 40, 1017 '#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.'), 1018 ]; 1019 $form['group_info']['label'] = [ 1020 '#type' => 'textfield', 1021 '#default_value' => $this->options['group_info']['label'], 1022 '#title' => $this->t('Label'), 1023 '#size' => 40, 1024 ]; 1025 $form['group_info']['description'] = [ 1026 '#type' => 'textfield', 1027 '#default_value' => $this->options['group_info']['description'], 1028 '#title' => $this->t('Description'), 1029 '#size' => 60, 1030 ]; 1031 $form['group_info']['optional'] = [ 1032 '#type' => 'checkbox', 1033 '#title' => $this->t('Optional'), 1034 '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'), 1035 '#default_value' => $this->options['group_info']['optional'], 1036 ]; 1037 $form['group_info']['multiple'] = [ 1038 '#type' => 'checkbox', 1039 '#title' => $this->t('Allow multiple selections'), 1040 '#description' => $this->t('Enable to allow users to select multiple items.'), 1041 '#default_value' => $this->options['group_info']['multiple'], 1042 ]; 1043 $form['group_info']['widget'] = [ 1044 '#type' => 'radios', 1045 '#default_value' => $this->options['group_info']['widget'], 1046 '#title' => $this->t('Widget type'), 1047 '#options' => [ 1048 'radios' => $this->t('Radios'), 1049 'select' => $this->t('Select'), 1050 ], 1051 '#description' => $this->t('Select which kind of widget will be used to render the group of filters'), 1052 ]; 1053 $form['group_info']['remember'] = [ 1054 '#type' => 'checkbox', 1055 '#title' => $this->t('Remember'), 1056 '#description' => $this->t('Remember the last setting the user gave this filter.'), 1057 '#default_value' => $this->options['group_info']['remember'], 1058 ]; 1059 1060 if (!empty($this->options['group_info']['identifier'])) { 1061 $identifier = $this->options['group_info']['identifier']; 1062 } 1063 else { 1064 $identifier = 'group_' . $this->options['expose']['identifier']; 1065 } 1066 $form['group_info']['identifier'] = [ 1067 '#type' => 'textfield', 1068 '#default_value' => $identifier, 1069 '#title' => $this->t('Filter identifier'), 1070 '#size' => 40, 1071 '#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.'), 1072 ]; 1073 $form['group_info']['label'] = [ 1074 '#type' => 'textfield', 1075 '#default_value' => $this->options['group_info']['label'], 1076 '#title' => $this->t('Label'), 1077 '#size' => 40, 1078 ]; 1079 $form['group_info']['optional'] = [ 1080 '#type' => 'checkbox', 1081 '#title' => $this->t('Optional'), 1082 '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'), 1083 '#default_value' => $this->options['group_info']['optional'], 1084 ]; 1085 $form['group_info']['widget'] = [ 1086 '#type' => 'radios', 1087 '#default_value' => $this->options['group_info']['widget'], 1088 '#title' => $this->t('Widget type'), 1089 '#options' => [ 1090 'radios' => $this->t('Radios'), 1091 'select' => $this->t('Select'), 1092 ], 1093 '#description' => $this->t('Select which kind of widget will be used to render the group of filters'), 1094 ]; 1095 $form['group_info']['remember'] = [ 1096 '#type' => 'checkbox', 1097 '#title' => $this->t('Remember'), 1098 '#description' => $this->t('Remember the last setting the user gave this filter.'), 1099 '#default_value' => $this->options['group_info']['remember'], 1100 ]; 1101 1102 // The string '- Any -' will not be rendered. 1103 // @see theme_views_ui_build_group_filter_form() 1104 $groups = ['All' => $this->t('- Any -')]; 1105 1106 // Provide 3 options to start when we are in a new group. 1107 if (count($this->options['group_info']['group_items']) == 0) { 1108 $this->options['group_info']['group_items'] = array_fill(1, 3, []); 1109 } 1110 1111 // After the general settings, comes a table with all the existent groups. 1112 $default_weight = 0; 1113 foreach ($this->options['group_info']['group_items'] as $item_id => $item) { 1114 if (!$form_state->isValueEmpty(['options', 'group_info', 'group_items', $item_id, 'remove'])) { 1115 continue; 1116 } 1117 // Each rows contains three widgets: 1118 // a) The title, where users define how they identify a pair of operator | value 1119 // b) The operator 1120 // c) The value (or values) to use in the filter with the selected operator 1121 1122 // In each row, we have to display the operator form and the value from 1123 // $row acts as a fake form to render each widget in a row. 1124 $row = []; 1125 $groups[$item_id] = $this->t('Grouping @id', ['@id' => $item_id]); 1126 $this->operatorForm($row, $form_state); 1127 // Force the operator form to be a select box. Some handlers uses 1128 // radios and they occupy a lot of space in a table row. 1129 $row['operator']['#type'] = 'select'; 1130 $row['operator']['#title'] = ''; 1131 $this->valueForm($row, $form_state); 1132 1133 // Fix the dependencies to update value forms when operators changes. This 1134 // is needed because forms are inside a new form and their IDs changes. 1135 // Dependencies are used when operator changes from to 'Between', 1136 // 'Not Between', etc, and two or more widgets are displayed. 1137 FormHelper::rewriteStatesSelector($row['value'], ':input[name="options[operator]"]', ':input[name="options[group_info][group_items][' . $item_id . '][operator]"]'); 1138 1139 // Set default values. 1140 $children = Element::children($row['value']); 1141 if (!empty($children)) { 1142 foreach ($children as $child) { 1143 if (!empty($row['value'][$child]['#states']['visible'])) { 1144 foreach ($row['value'][$child]['#states']['visible'] as $state) { 1145 if (isset($state[':input[name="options[group_info][group_items][' . $item_id . '][operator]"]'])) { 1146 $row['value'][$child]['#title'] = ''; 1147 1148 // Exit this loop and process the next child element. 1149 break; 1150 } 1151 } 1152 } 1153 1154 if (!empty($this->options['group_info']['group_items'][$item_id]['value'][$child])) { 1155 $row['value'][$child]['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'][$child]; 1156 } 1157 } 1158 } 1159 else { 1160 if (isset($this->options['group_info']['group_items'][$item_id]['value']) && $this->options['group_info']['group_items'][$item_id]['value'] != '') { 1161 $row['value']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value']; 1162 } 1163 } 1164 1165 if (!empty($this->options['group_info']['group_items'][$item_id]['operator'])) { 1166 $row['operator']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['operator']; 1167 } 1168 1169 $default_title = ''; 1170 if (!empty($this->options['group_info']['group_items'][$item_id]['title'])) { 1171 $default_title = $this->options['group_info']['group_items'][$item_id]['title']; 1172 } 1173 1174 // Per item group, we have a title that identifies it. 1175 $form['group_info']['group_items'][$item_id] = [ 1176 'title' => [ 1177 '#title' => $this->t('Label'), 1178 '#title_display' => 'invisible', 1179 '#type' => 'textfield', 1180 '#size' => 20, 1181 '#default_value' => $default_title, 1182 ], 1183 'operator' => $row['operator'], 1184 'value' => $row['value'], 1185 // No title is given here, since this input is never displayed. It is 1186 // only triggered by JavaScript. 1187 'remove' => [ 1188 '#type' => 'checkbox', 1189 '#id' => 'views-removed-' . $item_id, 1190 '#attributes' => ['class' => ['views-remove-checkbox']], 1191 '#default_value' => 0, 1192 ], 1193 'weight' => [ 1194 '#title' => $this->t('Weight'), 1195 '#title_display' => 'invisible', 1196 '#type' => 'weight', 1197 '#delta' => count($this->options['group_info']['group_items']), 1198 '#default_value' => $default_weight++, 1199 '#attributes' => ['class' => ['weight']], 1200 ], 1201 ]; 1202 } 1203 // From all groups, let chose which is the default. 1204 $form['group_info']['default_group'] = [ 1205 '#type' => 'radios', 1206 '#options' => $groups, 1207 '#default_value' => $this->options['group_info']['default_group'], 1208 '#required' => TRUE, 1209 '#attributes' => [ 1210 'class' => ['default-radios'], 1211 ], 1212 ]; 1213 // From all groups, let chose which is the default. 1214 $form['group_info']['default_group_multiple'] = [ 1215 '#type' => 'checkboxes', 1216 '#options' => $groups, 1217 '#default_value' => $this->options['group_info']['default_group_multiple'], 1218 '#attributes' => [ 1219 'class' => ['default-checkboxes'], 1220 ], 1221 ]; 1222 1223 $form['group_info']['add_group'] = [ 1224 '#prefix' => '<div class="views-build-group clear-block">', 1225 '#suffix' => '</div>', 1226 '#type' => 'submit', 1227 '#value' => $this->t('Add another item'), 1228 '#submit' => [[$this, 'addGroupForm']], 1229 ]; 1230 1231 $js = []; 1232 $js['tableDrag']['views-filter-groups']['weight'][0] = [ 1233 'target' => 'weight', 1234 'source' => NULL, 1235 'relationship' => 'sibling', 1236 'action' => 'order', 1237 'hidden' => TRUE, 1238 'limit' => 0, 1239 ]; 1240 $js_settings = $form_state->get('js_settings'); 1241 if ($js_settings && is_array($js)) { 1242 $js_settings = array_merge($js_settings, $js); 1243 } 1244 else { 1245 $js_settings = $js; 1246 } 1247 $form_state->set('js_settings', $js_settings); 1248 } 1249 1250 /** 1251 * Add a new group to the exposed filter groups. 1252 */ 1253 public function addGroupForm($form, FormStateInterface $form_state) { 1254 $item = &$this->options; 1255 1256 // Add a new row. 1257 $item['group_info']['group_items'][] = []; 1258 1259 $view = $form_state->get('view'); 1260 $display_id = $form_state->get('display_id'); 1261 $type = $form_state->get('type'); 1262 $id = $form_state->get('id'); 1263 $view->getExecutable()->setHandler($display_id, $type, $id, $item); 1264 1265 $view->cacheSet(); 1266 $form_state->set('rerender', TRUE); 1267 $form_state->setRebuild(); 1268 $form_state->get('force_build_group_options', TRUE); 1269 } 1270 1271 /** 1272 * Make some translations to a form item to make it more suitable to 1273 * exposing. 1274 */ 1275 protected function exposedTranslate(&$form, $type) { 1276 if (!isset($form['#type'])) { 1277 return; 1278 } 1279 1280 if ($form['#type'] == 'radios') { 1281 $form['#type'] = 'select'; 1282 } 1283 // Checkboxes don't work so well in exposed forms due to GET conversions. 1284 if ($form['#type'] == 'checkboxes') { 1285 if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) { 1286 $form['#type'] = 'select'; 1287 } 1288 if (!empty($this->options['expose']['multiple'])) { 1289 $form['#multiple'] = TRUE; 1290 } 1291 } 1292 if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) { 1293 unset($form['#multiple']); 1294 $form['#size'] = NULL; 1295 } 1296 1297 // Cleanup in case the translated element's (radios or checkboxes) display value contains html. 1298 if ($form['#type'] == 'select') { 1299 $this->prepareFilterSelectOptions($form['#options']); 1300 } 1301 1302 if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) { 1303 $form['#options'] = ['All' => $this->t('- Any -')] + $form['#options']; 1304 $form['#default_value'] = 'All'; 1305 } 1306 1307 if (!empty($this->options['expose']['required'])) { 1308 $form['#required'] = TRUE; 1309 } 1310 } 1311 1312 /** 1313 * Sanitizes the HTML select element's options. 1314 * 1315 * The function is recursive to support optgroups. 1316 */ 1317 protected function prepareFilterSelectOptions(&$options) { 1318 foreach ($options as $value => $label) { 1319 // Recurse for optgroups. 1320 if (is_array($label)) { 1321 $this->prepareFilterSelectOptions($options[$value]); 1322 } 1323 // FAPI has some special value to allow hierarchy. 1324 // @see _form_options_flatten 1325 elseif (is_object($label) && isset($label->option)) { 1326 $this->prepareFilterSelectOptions($options[$value]->option); 1327 } 1328 else { 1329 // Cast the label to a string since it can be an object. 1330 // @see \Drupal\Core\StringTranslation\TranslatableMarkup 1331 $options[$value] = strip_tags(Html::decodeEntities((string) $label)); 1332 } 1333 } 1334 } 1335 1336 /** 1337 * Tell the renderer about our exposed form. This only needs to be 1338 * overridden for particularly complex forms. And maybe not even then. 1339 * 1340 * @return array|null 1341 * For standard exposed filters. An array with the following keys: 1342 * - operator: The $form key of the operator. Set to NULL if no operator. 1343 * - value: The $form key of the value. Set to NULL if no value. 1344 * - label: The label to use for this piece. 1345 * For grouped exposed filters. An array with the following keys: 1346 * - value: The $form key of the value. Set to NULL if no value. 1347 * - label: The label to use for this piece. 1348 */ 1349 public function exposedInfo() { 1350 if (empty($this->options['exposed'])) { 1351 return; 1352 } 1353 1354 if ($this->isAGroup()) { 1355 return [ 1356 'value' => $this->options['group_info']['identifier'], 1357 'label' => $this->options['group_info']['label'], 1358 'description' => $this->options['group_info']['description'], 1359 ]; 1360 } 1361 1362 return [ 1363 'operator' => $this->options['expose']['operator_id'], 1364 'value' => $this->options['expose']['identifier'], 1365 'label' => $this->options['expose']['label'], 1366 'description' => $this->options['expose']['description'], 1367 ]; 1368 } 1369 1370 /** 1371 * Transform the input from a grouped filter into a standard filter. 1372 * 1373 * When a filter is a group, find the set of operator and values 1374 * that the chosen item represents, and inform views that a normal 1375 * filter was submitted by telling the operator and the value selected. 1376 * 1377 * The param $selected_group_id is only passed when the filter uses the 1378 * checkboxes widget, and this function will be called for each item 1379 * chosen in the checkboxes. 1380 */ 1381 public function convertExposedInput(&$input, $selected_group_id = NULL) { 1382 if ($this->isAGroup()) { 1383 // If it is already defined the selected group, use it. Only valid 1384 // when the filter uses checkboxes for widget. 1385 if (!empty($selected_group_id)) { 1386 $selected_group = $selected_group_id; 1387 } 1388 else { 1389 $selected_group = $input[$this->options['group_info']['identifier']]; 1390 } 1391 if ($selected_group == 'All' && !empty($this->options['group_info']['optional'])) { 1392 return NULL; 1393 } 1394 if ($selected_group != 'All' && empty($this->options['group_info']['group_items'][$selected_group])) { 1395 return FALSE; 1396 } 1397 if (isset($selected_group) && isset($this->options['group_info']['group_items'][$selected_group])) { 1398 $input[$this->options['expose']['operator']] = $this->options['group_info']['group_items'][$selected_group]['operator']; 1399 1400 // Value can be optional, For example for 'empty' and 'not empty' filters. 1401 if (isset($this->options['group_info']['group_items'][$selected_group]['value']) && $this->options['group_info']['group_items'][$selected_group]['value'] !== '') { 1402 $input[$this->options['group_info']['identifier']] = $this->options['group_info']['group_items'][$selected_group]['value']; 1403 } 1404 $this->options['expose']['use_operator'] = TRUE; 1405 1406 $this->group_info = $input[$this->options['group_info']['identifier']]; 1407 return TRUE; 1408 } 1409 else { 1410 return FALSE; 1411 } 1412 } 1413 } 1414 1415 /** 1416 * Returns the options available for a grouped filter that users checkboxes 1417 * as widget, and therefore has to be applied several times, one per 1418 * item selected. 1419 */ 1420 public function groupMultipleExposedInput(&$input) { 1421 if (!empty($input[$this->options['group_info']['identifier']])) { 1422 return array_filter($input[$this->options['group_info']['identifier']]); 1423 } 1424 return []; 1425 } 1426 1427 /** 1428 * Returns TRUE if users can select multiple groups items of a 1429 * grouped exposed filter. 1430 */ 1431 public function multipleExposedInput() { 1432 return $this->isAGroup() && !empty($this->options['group_info']['multiple']); 1433 } 1434 1435 /** 1436 * If set to remember exposed input in the session, store it there. 1437 * This function is similar to storeExposedInput but modified to 1438 * work properly when the filter is a group. 1439 */ 1440 public function storeGroupInput($input, $status) { 1441 if (!$this->isAGroup() || empty($this->options['group_info']['identifier'])) { 1442 return TRUE; 1443 } 1444 1445 if (empty($this->options['group_info']['remember'])) { 1446 return; 1447 } 1448 1449 // Figure out which display id is responsible for the filters, so we 1450 // know where to look for session stored values. 1451 $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display; 1452 1453 // False means that we got a setting that means to recurse ourselves, 1454 // so we should erase whatever happened to be there. 1455 if ($status === FALSE && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { 1456 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; 1457 1458 if (isset($session[$this->options['group_info']['identifier']])) { 1459 unset($session[$this->options['group_info']['identifier']]); 1460 } 1461 } 1462 1463 if ($status !== FALSE) { 1464 if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { 1465 $_SESSION['views'][$this->view->storage->id()][$display_id] = []; 1466 } 1467 1468 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; 1469 1470 $session[$this->options['group_info']['identifier']] = $input[$this->options['group_info']['identifier']]; 1471 } 1472 } 1473 1474 /** 1475 * Determines if the input from a filter should change the generated query. 1476 * 1477 * @param array $input 1478 * The exposed data for this view. 1479 * 1480 * @return bool 1481 * TRUE if the input for this filter should be included in the view query. 1482 * FALSE otherwise. 1483 */ 1484 public function acceptExposedInput($input) { 1485 if (empty($this->options['exposed'])) { 1486 return TRUE; 1487 } 1488 1489 if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) { 1490 $this->operator = $input[$this->options['expose']['operator_id']]; 1491 } 1492 1493 if (!empty($this->options['expose']['identifier'])) { 1494 if ($this->options['is_grouped']) { 1495 $value = $input[$this->options['group_info']['identifier']]; 1496 } 1497 else { 1498 $value = $input[$this->options['expose']['identifier']]; 1499 } 1500 1501 // Various ways to check for the absence of non-required input. 1502 if (empty($this->options['expose']['required'])) { 1503 if (($this->operator == 'empty' || $this->operator == 'not empty') && $value === '') { 1504 $value = ' '; 1505 } 1506 1507 if ($this->operator != 'empty' && $this->operator != 'not empty') { 1508 if ($value == 'All' || $value === []) { 1509 return FALSE; 1510 } 1511 1512 // If checkboxes are used to render this filter, do not include the 1513 // filter if no options are checked. 1514 if (is_array($value) && Checkboxes::detectEmptyCheckboxes($value)) { 1515 return FALSE; 1516 } 1517 } 1518 1519 if (!empty($this->alwaysMultiple) && $value === '') { 1520 return FALSE; 1521 } 1522 } 1523 if (isset($value)) { 1524 $this->value = $value; 1525 if (empty($this->alwaysMultiple) && empty($this->options['expose']['multiple']) && !is_array($value)) { 1526 $this->value = [$value]; 1527 } 1528 } 1529 else { 1530 return FALSE; 1531 } 1532 } 1533 1534 return TRUE; 1535 } 1536 1537 public function storeExposedInput($input, $status) { 1538 if (empty($this->options['exposed']) || empty($this->options['expose']['identifier'])) { 1539 return TRUE; 1540 } 1541 1542 if (empty($this->options['expose']['remember'])) { 1543 return; 1544 } 1545 1546 // Check if we store exposed value for current user. 1547 $user = \Drupal::currentUser(); 1548 $allowed_rids = empty($this->options['expose']['remember_roles']) ? [] : array_filter($this->options['expose']['remember_roles']); 1549 $intersect_rids = array_intersect(array_keys($allowed_rids), $user->getRoles()); 1550 if (empty($intersect_rids)) { 1551 return; 1552 } 1553 1554 // Figure out which display id is responsible for the filters, so we 1555 // know where to look for session stored values. 1556 $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display; 1557 1558 // shortcut test. 1559 $operator = !empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']); 1560 1561 // False means that we got a setting that means to recurse ourselves, 1562 // so we should erase whatever happened to be there. 1563 if (!$status && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { 1564 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; 1565 if ($operator && isset($session[$this->options['expose']['operator_id']])) { 1566 unset($session[$this->options['expose']['operator_id']]); 1567 } 1568 1569 if (isset($session[$this->options['expose']['identifier']])) { 1570 unset($session[$this->options['expose']['identifier']]); 1571 } 1572 } 1573 1574 if ($status) { 1575 if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { 1576 $_SESSION['views'][$this->view->storage->id()][$display_id] = []; 1577 } 1578 1579 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; 1580 1581 if ($operator && isset($input[$this->options['expose']['operator_id']])) { 1582 $session[$this->options['expose']['operator_id']] = $input[$this->options['expose']['operator_id']]; 1583 } 1584 1585 $session[$this->options['expose']['identifier']] = $input[$this->options['expose']['identifier']]; 1586 } 1587 } 1588 1589 /** 1590 * Add this filter to the query. 1591 * 1592 * Due to the nature of fapi, the value and the operator have an unintended 1593 * level of indirection. You will find them in $this->operator 1594 * and $this->value respectively. 1595 */ 1596 public function query() { 1597 $this->ensureMyTable(); 1598 $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", $this->value, $this->operator); 1599 } 1600 1601 /** 1602 * Can this filter be used in OR groups? 1603 * 1604 * Some filters have complicated where clauses that cannot be easily used 1605 * with OR groups. Some filters must also use HAVING which also makes 1606 * them not groupable. These filters will end up in a special group 1607 * if OR grouping is in use. 1608 * 1609 * @return bool 1610 */ 1611 public function canGroup() { 1612 return TRUE; 1613 } 1614 1615 /** 1616 * {@inheritdoc} 1617 */ 1618 public function getCacheMaxAge() { 1619 return Cache::PERMANENT; 1620 } 1621 1622 /** 1623 * {@inheritdoc} 1624 */ 1625 public function getCacheContexts() { 1626 $cache_contexts = []; 1627 // An exposed filter allows the user to change a view's filters. They accept 1628 // input from GET parameters, which are part of the URL. Hence a view with 1629 // an exposed filter is cacheable per URL. 1630 if ($this->isExposed()) { 1631 $cache_contexts[] = 'url'; 1632 } 1633 return $cache_contexts; 1634 } 1635 1636 /** 1637 * {@inheritdoc} 1638 */ 1639 public function getCacheTags() { 1640 return []; 1641 } 1642 1643 /** 1644 * {@inheritdoc} 1645 */ 1646 public function validate() { 1647 if (!empty($this->options['exposed']) && $error = $this->validateIdentifier($this->options['expose']['identifier'])) { 1648 return [$error]; 1649 } 1650 } 1651 1652 /** 1653 * Filter by no empty values, though allow the use of (string) "0". 1654 * 1655 * @param string $var 1656 * The variable to evaluate. 1657 * 1658 * @return bool 1659 * TRUE if the value is equal to an empty string, FALSE otherwise. 1660 */ 1661 protected static function arrayFilterZero($var) { 1662 if (is_int($var)) { 1663 return $var != 0; 1664 } 1665 return trim($var) != ''; 1666 } 1667 1668} 1669 1670/** 1671 * @} 1672 */ 1673