3 namespace Drupal\views\Plugin\views\filter;
5 use Drupal\Core\Cache\Cache;
6 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;
18 * @defgroup views_filter_handlers Views filter handler plugins
20 * Plugins that handle views filtering.
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.
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.
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
39 * @ingroup views_plugins
44 * Base class for Views filters handler plugins.
46 abstract class FilterPluginBase extends HandlerBase implements CacheableDependencyInterface {
49 * Contains the actual value of the field,either configured in the views ui
50 * or entered in the exposed filters.
55 * Contains the operator which is used on the query.
59 public $operator = '=';
62 * Contains the information of the selected item in a grouped filter.
64 public $group_info = NULL;
68 * Disable the possibility to force a single value.
70 protected $alwaysMultiple = FALSE;
74 * Disable the possibility to use operators.
76 public $no_operator = FALSE;
80 * Disable the possibility to allow a exposed input to be optional.
82 public $always_required = FALSE;
85 * Overrides \Drupal\views\Plugin\views\HandlerBase::init().
87 * Provide some extra help to get the operator/value easier to use.
89 * This likely has to be overridden by filters which are more complex
90 * than simple operator/value.
92 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
93 parent::init($view, $display, $options);
95 $this->operator = $this->options['operator'];
96 $this->value = $this->options['value'];
97 $this->group_info = $this->options['group_info']['default_group'];
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'];
104 if ($this->multipleExposedInput()) {
105 $this->group_info = array_filter($options['group_info']['default_group_multiple']);
106 $this->options['expose']['multiple'] = TRUE;
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;
117 protected function defineOptions() {
118 $options = parent::defineOptions();
120 $options['operator'] = ['default' => '='];
121 $options['value'] = ['default' => ''];
122 $options['group'] = ['default' => '1'];
123 $options['exposed'] = ['default' => FALSE];
124 $options['expose'] = [
126 'operator_id' => ['default' => FALSE],
127 'label' => ['default' => ''],
128 'description' => ['default' => ''],
129 'use_operator' => ['default' => FALSE],
130 'operator' => ['default' => ''],
131 'identifier' => ['default' => ''],
132 'required' => ['default' => FALSE],
133 'remember' => ['default' => FALSE],
134 'multiple' => ['default' => FALSE],
135 'remember_roles' => [
137 RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID,
143 // A group is a combination of a filter, an operator and a value
144 // operating like a single filter.
145 // Users can choose from a select box which group they want to apply.
146 // Views will filter the view according to the defined values.
147 // Because it acts as a standard filter, we have to define
148 // an identifier and other settings like the widget and the label.
149 // This settings are saved in another array to allow users to switch
150 // between a normal filter and a group of filters with a single click.
151 $options['is_grouped'] = ['default' => FALSE];
152 $options['group_info'] = [
154 'label' => ['default' => ''],
155 'description' => ['default' => ''],
156 'identifier' => ['default' => ''],
157 'optional' => ['default' => TRUE],
158 'widget' => ['default' => 'select'],
159 'multiple' => ['default' => FALSE],
160 'remember' => ['default' => 0],
161 'default_group' => ['default' => 'All'],
162 'default_group_multiple' => ['default' => []],
163 'group_items' => ['default' => []],
171 * Display the filter on the administrative summary
173 public function adminSummary() {
174 return $this->operator . ' ' . $this->value;
178 * Determine if a filter can be exposed.
180 public function canExpose() {
185 * Determine if a filter can be converted into a group.
186 * Only exposed filters with operators available can be converted into groups.
188 protected function canBuildGroup() {
189 return $this->isExposed() && (count($this->operatorOptions()) > 0);
193 * Returns TRUE if the exposed filter works like a grouped filter.
195 public function isAGroup() {
196 return $this->isExposed() && !empty($this->options['is_grouped']);
200 * Provide the basic form which calls through to subforms.
201 * If overridden, it is best to call through to the parent,
202 * or to at least make sure all of the functions in this form
205 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
206 parent::buildOptionsForm($form, $form_state);
207 if ($this->canExpose()) {
208 $this->showExposeButton($form, $form_state);
210 if ($this->canBuildGroup()) {
211 $this->showBuildGroupButton($form, $form_state);
213 $form['clear_markup_start'] = [
214 '#markup' => '<div class="clearfix">',
216 if ($this->isAGroup()) {
217 if ($this->canBuildGroup()) {
218 $form['clear_markup_start'] = [
219 '#markup' => '<div class="clearfix">',
221 // Render the build group form.
222 $this->showBuildGroupForm($form, $form_state);
223 $form['clear_markup_end'] = [
224 '#markup' => '</div>',
229 // Add the subform from operatorForm().
230 $this->showOperatorForm($form, $form_state);
231 // Add the subform from valueForm().
232 $this->showValueForm($form, $form_state);
233 $form['clear_markup_end'] = [
234 '#markup' => '</div>',
236 if ($this->canExpose()) {
237 // Add the subform from buildExposeForm().
238 $this->showExposeForm($form, $form_state);
244 * Simple validate handler
246 public function validateOptionsForm(&$form, FormStateInterface $form_state) {
247 $this->operatorValidate($form, $form_state);
248 $this->valueValidate($form, $form_state);
249 if (!empty($this->options['exposed']) && !$this->isAGroup()) {
250 $this->validateExposeForm($form, $form_state);
252 if ($this->isAGroup()) {
253 $this->buildGroupValidate($form, $form_state);
258 * Simple submit handler
260 public function submitOptionsForm(&$form, FormStateInterface $form_state) {
261 // Do not store these values.
262 $form_state->unsetValue('expose_button');
263 $form_state->unsetValue('group_button');
265 if (!$this->isAGroup()) {
266 $this->operatorSubmit($form, $form_state);
267 $this->valueSubmit($form, $form_state);
269 if (!empty($this->options['exposed'])) {
270 $this->submitExposeForm($form, $form_state);
272 if ($this->isAGroup()) {
273 $this->buildGroupSubmit($form, $form_state);
278 * Shortcut to display the operator form.
280 public function showOperatorForm(&$form, FormStateInterface $form_state) {
281 $this->operatorForm($form, $form_state);
282 $form['operator']['#prefix'] = '<div class="views-group-box views-left-30">';
283 $form['operator']['#suffix'] = '</div>';
287 * Options form subform for setting the operator.
289 * This may be overridden by child classes, and it must
290 * define $form['operator'];
292 * @see buildOptionsForm()
294 protected function operatorForm(&$form, FormStateInterface $form_state) {
295 $options = $this->operatorOptions();
296 if (!empty($options)) {
297 $form['operator'] = [
298 '#type' => count($options) < 10 ? 'radios' : 'select',
299 '#title' => $this->t('Operator'),
300 '#default_value' => $this->operator,
301 '#options' => $options,
307 * Provide a list of options for the default operator form.
308 * Should be overridden by classes that don't override operatorForm
310 public function operatorOptions() {
315 * Validate the operator form.
317 protected function operatorValidate($form, FormStateInterface $form_state) {}
320 * Perform any necessary changes to the form values prior to storage.
321 * There is no need for this function to actually store the data.
323 public function operatorSubmit($form, FormStateInterface $form_state) {}
326 * Shortcut to display the value form.
328 protected function showValueForm(&$form, FormStateInterface $form_state) {
329 $this->valueForm($form, $form_state);
330 if (empty($this->no_operator)) {
331 $form['value']['#prefix'] = '<div class="views-group-box views-right-70">' . (isset($form['value']['#prefix']) ? $form['value']['#prefix'] : '');
332 $form['value']['#suffix'] = (isset($form['value']['#suffix']) ? $form['value']['#suffix'] : '') . '</div>';
337 * Options form subform for setting options.
339 * This should be overridden by all child classes and it must
340 * define $form['value']
342 * @see buildOptionsForm()
344 protected function valueForm(&$form, FormStateInterface $form_state) {
349 * Validate the options form.
351 protected function valueValidate($form, FormStateInterface $form_state) {}
354 * Perform any necessary changes to the form values prior to storage.
355 * There is no need for this function to actually store the data.
357 protected function valueSubmit($form, FormStateInterface $form_state) {}
360 * Shortcut to display the exposed options form.
362 public function showBuildGroupForm(&$form, FormStateInterface $form_state) {
363 if (empty($this->options['is_grouped'])) {
367 $this->buildExposedFiltersGroupForm($form, $form_state);
369 // When we click the expose button, we add new gadgets to the form but they
370 // have no data in POST so their defaults get wiped out. This prevents
371 // these defaults from getting wiped out. This setting will only be TRUE
372 // during a 2nd pass rerender.
373 if ($form_state->get('force_build_group_options')) {
374 foreach (Element::children($form['group_info']) as $id) {
375 if (isset($form['group_info'][$id]['#default_value']) && !isset($form['group_info'][$id]['#value'])) {
376 $form['group_info'][$id]['#value'] = $form['group_info'][$id]['#default_value'];
383 * Shortcut to display the build_group/hide button.
385 protected function showBuildGroupButton(&$form, FormStateInterface $form_state) {
387 $form['group_button'] = [
388 '#prefix' => '<div class="views-grouped clearfix">',
389 '#suffix' => '</div>',
390 // Should always come after the description and the relationship.
394 $grouped_description = $this->t('Grouped filters allow a choice between predefined operator|value pairs.');
395 $form['group_button']['radios'] = [
396 '#theme_wrappers' => ['container'],
397 '#attributes' => ['class' => ['js-only']],
399 $form['group_button']['radios']['radios'] = [
400 '#title' => $this->t('Filter type to expose'),
401 '#description' => $grouped_description,
404 $this->t('Single filter'),
405 $this->t('Grouped filters'),
409 if (empty($this->options['is_grouped'])) {
410 $form['group_button']['markup'] = [
411 '#markup' => '<div class="description grouped-description">' . $grouped_description . '</div>',
413 $form['group_button']['button'] = [
414 '#limit_validation_errors' => [],
416 '#value' => $this->t('Grouped filters'),
417 '#submit' => [[$this, 'buildGroupForm']],
419 $form['group_button']['radios']['radios']['#default_value'] = 0;
422 $form['group_button']['button'] = [
423 '#limit_validation_errors' => [],
425 '#value' => $this->t('Single filter'),
426 '#submit' => [[$this, 'buildGroupForm']],
428 $form['group_button']['radios']['radios']['#default_value'] = 1;
433 * Displays the Build Group form.
435 public function buildGroupForm($form, FormStateInterface $form_state) {
436 $item = &$this->options;
437 // flip. If the filter was a group, set back to a standard filter.
438 $item['is_grouped'] = empty($item['is_grouped']);
440 // If necessary, set new defaults:
441 if ($item['is_grouped']) {
442 $this->buildGroupOptions();
445 $view = $form_state->get('view');
446 $display_id = $form_state->get('display_id');
447 $type = $form_state->get('type');
448 $id = $form_state->get('id');
449 $view->getExecutable()->setHandler($display_id, $type, $id, $item);
451 $view->addFormToStack($form_state->get('form_key'), $display_id, $type, $id, TRUE, TRUE);
454 $form_state->set('rerender', TRUE);
455 $form_state->setRebuild();
456 $form_state->get('force_build_group_options', TRUE);
460 * Shortcut to display the expose/hide button.
462 public function showExposeButton(&$form, FormStateInterface $form_state) {
463 $form['expose_button'] = [
464 '#prefix' => '<div class="views-expose clearfix">',
465 '#suffix' => '</div>',
466 // Should always come after the description and the relationship.
470 // Add a checkbox for JS users, which will have behavior attached to it
471 // so it can replace the button.
472 $form['expose_button']['checkbox'] = [
473 '#theme_wrappers' => ['container'],
474 '#attributes' => ['class' => ['js-only']],
476 $form['expose_button']['checkbox']['checkbox'] = [
477 '#title' => $this->t('Expose this filter to visitors, to allow them to change it'),
478 '#type' => 'checkbox',
481 // Then add the button itself.
482 if (empty($this->options['exposed'])) {
483 $form['expose_button']['markup'] = [
484 '#markup' => '<div class="description exposed-description">' . $this->t('This filter is not exposed. Expose it to allow the users to change it.') . '</div>',
486 $form['expose_button']['button'] = [
487 '#limit_validation_errors' => [],
489 '#value' => $this->t('Expose filter'),
490 '#submit' => [[$this, 'displayExposedForm']],
492 $form['expose_button']['checkbox']['checkbox']['#default_value'] = 0;
495 $form['expose_button']['markup'] = [
496 '#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>',
498 $form['expose_button']['button'] = [
499 '#limit_validation_errors' => [],
501 '#value' => $this->t('Hide filter'),
502 '#submit' => [[$this, 'displayExposedForm']],
504 $form['expose_button']['checkbox']['checkbox']['#default_value'] = 1;
509 * Options form subform for exposed filter options.
511 * @see buildOptionsForm()
513 public function buildExposeForm(&$form, FormStateInterface $form_state) {
514 $form['#theme'] = 'views_ui_expose_filter_form';
515 // #flatten will move everything from $form['expose'][$key] to $form[$key]
516 // prior to rendering. That's why the preRender for it needs to run first,
517 // so that when the next preRender (the one for fieldsets) runs, it gets
518 // the flattened data.
519 array_unshift($form['#pre_render'], [get_class($this), 'preRenderFlattenData']);
520 $form['expose']['#flatten'] = TRUE;
522 if (empty($this->always_required)) {
523 $form['expose']['required'] = [
524 '#type' => 'checkbox',
525 '#title' => $this->t('Required'),
526 '#default_value' => $this->options['expose']['required'],
530 $form['expose']['required'] = [
535 $form['expose']['label'] = [
536 '#type' => 'textfield',
537 '#default_value' => $this->options['expose']['label'],
538 '#title' => $this->t('Label'),
542 $form['expose']['description'] = [
543 '#type' => 'textfield',
544 '#default_value' => $this->options['expose']['description'],
545 '#title' => $this->t('Description'),
549 if (!empty($form['operator']['#type'])) {
550 // Increase the width of the left (operator) column.
551 $form['operator']['#prefix'] = '<div class="views-group-box views-left-40">';
552 $form['operator']['#suffix'] = '</div>';
553 $form['value']['#prefix'] = '<div class="views-group-box views-right-60">';
554 $form['value']['#suffix'] = '</div>';
556 $form['expose']['use_operator'] = [
557 '#type' => 'checkbox',
558 '#title' => $this->t('Expose operator'),
559 '#description' => $this->t('Allow the user to choose the operator.'),
560 '#default_value' => !empty($this->options['expose']['use_operator']),
562 $form['expose']['operator_id'] = [
563 '#type' => 'textfield',
564 '#default_value' => $this->options['expose']['operator_id'],
565 '#title' => $this->t('Operator identifier'),
567 '#description' => $this->t('This will appear in the URL after the ? to identify this operator.'),
570 ':input[name="options[expose][use_operator]"]' => ['checked' => TRUE],
576 $form['expose']['operator_id'] = [
582 if (empty($this->alwaysMultiple)) {
583 $form['expose']['multiple'] = [
584 '#type' => 'checkbox',
585 '#title' => $this->t('Allow multiple selections'),
586 '#description' => $this->t('Enable to allow users to select multiple items.'),
587 '#default_value' => $this->options['expose']['multiple'],
590 $form['expose']['remember'] = [
591 '#type' => 'checkbox',
592 '#title' => $this->t('Remember the last selection'),
593 '#description' => $this->t('Enable to remember the last selection made by the user.'),
594 '#default_value' => $this->options['expose']['remember'],
597 $role_options = array_map('\Drupal\Component\Utility\Html::escape', user_role_names());
598 $form['expose']['remember_roles'] = [
599 '#type' => 'checkboxes',
600 '#title' => $this->t('User roles'),
601 '#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.'),
602 '#default_value' => $this->options['expose']['remember_roles'],
603 '#options' => $role_options,
606 ':input[name="options[expose][remember]"]' => ['checked' => FALSE],
611 $form['expose']['identifier'] = [
612 '#type' => 'textfield',
613 '#default_value' => $this->options['expose']['identifier'],
614 '#title' => $this->t('Filter identifier'),
616 '#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.'),
621 * Validate the options form.
623 public function validateExposeForm($form, FormStateInterface $form_state) {
624 $identifier = $form_state->getValue(['options', 'expose', 'identifier']);
625 $this->validateIdentifier($identifier, $form_state, $form['expose']['identifier']);
629 * Determines if the given grouped filter entry has a valid value.
631 * @param array $group
632 * A group entry as defined by buildGroupForm().
636 protected function hasValidGroupedValue(array $group) {
637 $operators = $this->operators();
638 if ($operators[$group['operator']]['values'] == 0) {
639 // Some filters, such as "is empty," do not require a value to be
640 // specified in order to be valid entries.
644 if (is_string($group['value'])) {
645 return trim($group['value']) != '';
647 elseif (is_array($group['value'])) {
648 // Some filters allow multiple options to be selected (for example, node
649 // types). Ensure at least the minimum number of values is present for
650 // this entry to be considered valid.
651 $min_values = $operators[$group['operator']]['values'];
652 $actual_values = count(array_filter($group['value'], 'static::arrayFilterZero'));
653 return $actual_values >= $min_values;
661 * Validate the build group options form.
663 protected function buildGroupValidate($form, FormStateInterface $form_state) {
664 if (!$form_state->isValueEmpty(['options', 'group_info'])) {
665 $identifier = $form_state->getValue(['options', 'group_info', 'identifier']);
666 $this->validateIdentifier($identifier, $form_state, $form['group_info']['identifier']);
669 if ($group_items = $form_state->getValue(['options', 'group_info', 'group_items'])) {
670 foreach ($group_items as $id => $group) {
671 if (empty($group['remove'])) {
672 $has_valid_value = $this->hasValidGroupedValue($group);
673 if ($has_valid_value && $group['title'] == '') {
674 $operators = $this->operators();
675 if ($operators[$group['operator']]['values'] == 0) {
676 $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required for the specified operator.'));
679 $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required if the value for this item is defined.'));
682 if (!$has_valid_value && $group['title'] != '') {
683 $form_state->setError($form['group_info']['group_items'][$id]['value'], $this->t('A value is required if the label for this item is defined.'));
691 * Validates a filter identifier.
693 * Sets the form error if $form_state is passed or a error string if
694 * $form_state is not passed.
696 * @param string $identifier
697 * The identifier to check.
698 * @param \Drupal\Core\Form\FormStateInterface $form_state
699 * @param array $form_group
700 * The form element to set any errors on.
704 protected function validateIdentifier($identifier, FormStateInterface $form_state = NULL, &$form_group = []) {
706 if (empty($identifier)) {
707 $error = $this->t('The identifier is required if the filter is exposed.');
709 elseif ($identifier == 'value') {
710 $error = $this->t('This identifier is not allowed.');
712 elseif (preg_match('/[^a-zA-z0-9_~\.\-]/', $identifier)) {
713 $error = $this->t('This identifier has illegal characters.');
716 if ($form_state && !$this->view->display_handler->isIdentifierUnique($form_state->get('id'), $identifier)) {
717 $error = $this->t('This identifier is used by another handler.');
720 if (!empty($form_state) && !empty($error)) {
721 $form_state->setError($form_group, $error);
727 * Save new group items, re-enumerates and remove groups marked to delete.
729 protected function buildGroupSubmit($form, FormStateInterface $form_state) {
731 $group_items = $form_state->getValue(['options', 'group_info', 'group_items']);
732 uasort($group_items, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
733 // Filter out removed items.
735 // Start from 1 to avoid problems with #default_value in the widget.
737 $new_default = 'All';
738 foreach ($group_items as $id => $group) {
739 if (empty($group['remove'])) {
741 unset($group['remove']);
742 unset($group['weight']);
743 $groups[$new_id] = $group;
745 if ($form_state->getValue(['options', 'group_info', 'default_group']) == $id) {
746 $new_default = $new_id;
751 if ($new_default != 'All') {
752 $form_state->setValue(['options', 'group_info', 'default_group'], $new_default);
754 $filter_default_multiple = $form_state->getValue(['options', 'group_info', 'default_group_multiple']);
755 $form_state->setValue(['options', 'group_info', 'default_group_multiple'], array_filter($filter_default_multiple));
757 $form_state->setValue(['options', 'group_info', 'group_items'], $groups);
761 * Provide default options for exposed filters.
763 public function defaultExposeOptions() {
764 $this->options['expose'] = [
765 'use_operator' => FALSE,
766 'operator' => $this->options['id'] . '_op',
767 'identifier' => $this->options['id'],
768 'label' => $this->definition['title'],
769 'description' => NULL,
777 * Provide default options for exposed filters.
779 protected function buildGroupOptions() {
780 $this->options['group_info'] = [
781 'label' => $this->definition['title'],
782 'description' => NULL,
783 'identifier' => $this->options['id'],
785 'widget' => 'select',
788 'default_group' => 'All',
789 'default_group_multiple' => [],
795 * Build a form containing a group of operator | values to apply as a
798 public function groupForm(&$form, FormStateInterface $form_state) {
799 if (!empty($this->options['group_info']['optional']) && !$this->multipleExposedInput()) {
800 $groups = ['All' => $this->t('- Any -')];
802 foreach ($this->options['group_info']['group_items'] as $id => $group) {
803 if (!empty($group['title'])) {
804 $groups[$id] = $id != 'All' ? $this->t($group['title']) : $group['title'];
808 if (count($groups)) {
809 $value = $this->options['group_info']['identifier'];
812 '#title' => $this->options['group_info']['label'],
813 '#type' => $this->options['group_info']['widget'],
814 '#default_value' => $this->group_info,
815 '#options' => $groups,
817 if (!empty($this->options['group_info']['multiple'])) {
818 if (count($groups) < 5) {
819 $form[$value]['#type'] = 'checkboxes';
822 $form[$value]['#type'] = 'select';
823 $form[$value]['#size'] = 5;
824 $form[$value]['#multiple'] = TRUE;
826 unset($form[$value]['#default_value']);
827 $user_input = $form_state->getUserInput();
828 if (empty($user_input)) {
829 $user_input[$value] = $this->group_info;
830 $form_state->setUserInput($user_input);
834 $this->options['expose']['label'] = '';
840 * Render our chunk of the exposed filter form when selecting
842 * You can override this if it doesn't do what you expect.
844 public function buildExposedForm(&$form, FormStateInterface $form_state) {
845 if (empty($this->options['exposed'])) {
849 // Build the exposed form, when its based on an operator.
850 if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id'])) {
851 $operator = $this->options['expose']['operator_id'];
852 $this->operatorForm($form, $form_state);
853 $form[$operator] = $form['operator'];
855 $this->exposedTranslate($form[$operator], 'operator');
857 unset($form['operator']);
860 // Build the form and set the value based on the identifier.
861 if (!empty($this->options['expose']['identifier'])) {
862 $value = $this->options['expose']['identifier'];
863 $this->valueForm($form, $form_state);
864 $form[$value] = $form['value'];
866 if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
867 unset($form[$value]['#title']);
870 $this->exposedTranslate($form[$value], 'value');
872 if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
873 unset($form[$value]['#default_value']);
876 if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
877 $form[$value]['#default_value'] = 'All';
880 if ($value != 'value') {
881 unset($form['value']);
887 * Build the form to let users create the group of exposed filters.
888 * This form is displayed when users click on button 'Build group'
890 protected function buildExposedFiltersGroupForm(&$form, FormStateInterface $form_state) {
891 if (empty($this->options['exposed']) || empty($this->options['is_grouped'])) {
894 $form['#theme'] = 'views_ui_build_group_filter_form';
896 // #flatten will move everything from $form['group_info'][$key] to $form[$key]
897 // prior to rendering. That's why the preRender for it needs to run first,
898 // so that when the next preRender (the one for fieldsets) runs, it gets
899 // the flattened data.
900 array_unshift($form['#pre_render'], [get_class($this), 'preRenderFlattenData']);
901 $form['group_info']['#flatten'] = TRUE;
903 if (!empty($this->options['group_info']['identifier'])) {
904 $identifier = $this->options['group_info']['identifier'];
907 $identifier = 'group_' . $this->options['expose']['identifier'];
909 $form['group_info']['identifier'] = [
910 '#type' => 'textfield',
911 '#default_value' => $identifier,
912 '#title' => $this->t('Filter identifier'),
914 '#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.'),
916 $form['group_info']['label'] = [
917 '#type' => 'textfield',
918 '#default_value' => $this->options['group_info']['label'],
919 '#title' => $this->t('Label'),
922 $form['group_info']['description'] = [
923 '#type' => 'textfield',
924 '#default_value' => $this->options['group_info']['description'],
925 '#title' => $this->t('Description'),
928 $form['group_info']['optional'] = [
929 '#type' => 'checkbox',
930 '#title' => $this->t('Optional'),
931 '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
932 '#default_value' => $this->options['group_info']['optional'],
934 $form['group_info']['multiple'] = [
935 '#type' => 'checkbox',
936 '#title' => $this->t('Allow multiple selections'),
937 '#description' => $this->t('Enable to allow users to select multiple items.'),
938 '#default_value' => $this->options['group_info']['multiple'],
940 $form['group_info']['widget'] = [
942 '#default_value' => $this->options['group_info']['widget'],
943 '#title' => $this->t('Widget type'),
945 'radios' => $this->t('Radios'),
946 'select' => $this->t('Select'),
948 '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
950 $form['group_info']['remember'] = [
951 '#type' => 'checkbox',
952 '#title' => $this->t('Remember'),
953 '#description' => $this->t('Remember the last setting the user gave this filter.'),
954 '#default_value' => $this->options['group_info']['remember'],
957 if (!empty($this->options['group_info']['identifier'])) {
958 $identifier = $this->options['group_info']['identifier'];
961 $identifier = 'group_' . $this->options['expose']['identifier'];
963 $form['group_info']['identifier'] = [
964 '#type' => 'textfield',
965 '#default_value' => $identifier,
966 '#title' => $this->t('Filter identifier'),
968 '#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.'),
970 $form['group_info']['label'] = [
971 '#type' => 'textfield',
972 '#default_value' => $this->options['group_info']['label'],
973 '#title' => $this->t('Label'),
976 $form['group_info']['optional'] = [
977 '#type' => 'checkbox',
978 '#title' => $this->t('Optional'),
979 '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
980 '#default_value' => $this->options['group_info']['optional'],
982 $form['group_info']['widget'] = [
984 '#default_value' => $this->options['group_info']['widget'],
985 '#title' => $this->t('Widget type'),
987 'radios' => $this->t('Radios'),
988 'select' => $this->t('Select'),
990 '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
992 $form['group_info']['remember'] = [
993 '#type' => 'checkbox',
994 '#title' => $this->t('Remember'),
995 '#description' => $this->t('Remember the last setting the user gave this filter.'),
996 '#default_value' => $this->options['group_info']['remember'],
999 // The string '- Any -' will not be rendered.
1000 // @see theme_views_ui_build_group_filter_form()
1001 $groups = ['All' => $this->t('- Any -')];
1003 // Provide 3 options to start when we are in a new group.
1004 if (count($this->options['group_info']['group_items']) == 0) {
1005 $this->options['group_info']['group_items'] = array_fill(1, 3, []);
1008 // After the general settings, comes a table with all the existent groups.
1009 $default_weight = 0;
1010 foreach ($this->options['group_info']['group_items'] as $item_id => $item) {
1011 if (!$form_state->isValueEmpty(['options', 'group_info', 'group_items', $item_id, 'remove'])) {
1014 // Each rows contains three widgets:
1015 // a) The title, where users define how they identify a pair of operator | value
1017 // c) The value (or values) to use in the filter with the selected operator
1019 // In each row, we have to display the operator form and the value from
1020 // $row acts as a fake form to render each widget in a row.
1022 $groups[$item_id] = $this->t('Grouping @id', ['@id' => $item_id]);
1023 $this->operatorForm($row, $form_state);
1024 // Force the operator form to be a select box. Some handlers uses
1025 // radios and they occupy a lot of space in a table row.
1026 $row['operator']['#type'] = 'select';
1027 $row['operator']['#title'] = '';
1028 $this->valueForm($row, $form_state);
1030 // Fix the dependencies to update value forms when operators changes. This
1031 // is needed because forms are inside a new form and their IDs changes.
1032 // Dependencies are used when operator changes from to 'Between',
1033 // 'Not Between', etc, and two or more widgets are displayed.
1034 FormHelper::rewriteStatesSelector($row['value'], ':input[name="options[operator]"]', ':input[name="options[group_info][group_items][' . $item_id . '][operator]"]');
1036 // Set default values.
1037 $children = Element::children($row['value']);
1038 if (!empty($children)) {
1039 foreach ($children as $child) {
1040 if (!empty($row['value'][$child]['#states']['visible'])) {
1041 foreach ($row['value'][$child]['#states']['visible'] as $state) {
1042 if (isset($state[':input[name="options[group_info][group_items][' . $item_id . '][operator]"]'])) {
1043 $row['value'][$child]['#title'] = '';
1045 // Exit this loop and process the next child element.
1051 if (!empty($this->options['group_info']['group_items'][$item_id]['value'][$child])) {
1052 $row['value'][$child]['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'][$child];
1057 if (isset($this->options['group_info']['group_items'][$item_id]['value']) && $this->options['group_info']['group_items'][$item_id]['value'] != '') {
1058 $row['value']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'];
1062 if (!empty($this->options['group_info']['group_items'][$item_id]['operator'])) {
1063 $row['operator']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['operator'];
1066 $default_title = '';
1067 if (!empty($this->options['group_info']['group_items'][$item_id]['title'])) {
1068 $default_title = $this->options['group_info']['group_items'][$item_id]['title'];
1071 // Per item group, we have a title that identifies it.
1072 $form['group_info']['group_items'][$item_id] = [
1074 '#title' => $this->t('Label'),
1075 '#title_display' => 'invisible',
1076 '#type' => 'textfield',
1078 '#default_value' => $default_title,
1080 'operator' => $row['operator'],
1081 'value' => $row['value'],
1082 // No title is given here, since this input is never displayed. It is
1083 // only triggered by JavaScript.
1085 '#type' => 'checkbox',
1086 '#id' => 'views-removed-' . $item_id,
1087 '#attributes' => ['class' => ['views-remove-checkbox']],
1088 '#default_value' => 0,
1091 '#title' => $this->t('Weight'),
1092 '#title_display' => 'invisible',
1093 '#type' => 'weight',
1094 '#delta' => count($this->options['group_info']['group_items']),
1095 '#default_value' => $default_weight++,
1096 '#attributes' => ['class' => ['weight']],
1100 // From all groups, let chose which is the default.
1101 $form['group_info']['default_group'] = [
1102 '#type' => 'radios',
1103 '#options' => $groups,
1104 '#default_value' => $this->options['group_info']['default_group'],
1105 '#required' => TRUE,
1107 'class' => ['default-radios'],
1110 // From all groups, let chose which is the default.
1111 $form['group_info']['default_group_multiple'] = [
1112 '#type' => 'checkboxes',
1113 '#options' => $groups,
1114 '#default_value' => $this->options['group_info']['default_group_multiple'],
1116 'class' => ['default-checkboxes'],
1120 $form['group_info']['add_group'] = [
1121 '#prefix' => '<div class="views-build-group clear-block">',
1122 '#suffix' => '</div>',
1123 '#type' => 'submit',
1124 '#value' => $this->t('Add another item'),
1125 '#submit' => [[$this, 'addGroupForm']],
1129 $js['tableDrag']['views-filter-groups']['weight'][0] = [
1130 'target' => 'weight',
1132 'relationship' => 'sibling',
1133 'action' => 'order',
1137 $js_settings = $form_state->get('js_settings');
1138 if ($js_settings && is_array($js)) {
1139 $js_settings = array_merge($js_settings, $js);
1144 $form_state->set('js_settings', $js_settings);
1148 * Add a new group to the exposed filter groups.
1150 public function addGroupForm($form, FormStateInterface $form_state) {
1151 $item = &$this->options;
1154 $item['group_info']['group_items'][] = [];
1156 $view = $form_state->get('view');
1157 $display_id = $form_state->get('display_id');
1158 $type = $form_state->get('type');
1159 $id = $form_state->get('id');
1160 $view->getExecutable()->setHandler($display_id, $type, $id, $item);
1163 $form_state->set('rerender', TRUE);
1164 $form_state->setRebuild();
1165 $form_state->get('force_build_group_options', TRUE);
1170 * Make some translations to a form item to make it more suitable to
1173 protected function exposedTranslate(&$form, $type) {
1174 if (!isset($form['#type'])) {
1178 if ($form['#type'] == 'radios') {
1179 $form['#type'] = 'select';
1181 // Checkboxes don't work so well in exposed forms due to GET conversions.
1182 if ($form['#type'] == 'checkboxes') {
1183 if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
1184 $form['#type'] = 'select';
1186 if (!empty($this->options['expose']['multiple'])) {
1187 $form['#multiple'] = TRUE;
1190 if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
1191 unset($form['#multiple']);
1192 $form['#size'] = NULL;
1195 // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
1196 if ($form['#type'] == 'select') {
1197 $this->prepareFilterSelectOptions($form['#options']);
1200 if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
1201 $form['#options'] = ['All' => $this->t('- Any -')] + $form['#options'];
1202 $form['#default_value'] = 'All';
1205 if (!empty($this->options['expose']['required'])) {
1206 $form['#required'] = TRUE;
1212 * Sanitizes the HTML select element's options.
1214 * The function is recursive to support optgroups.
1216 protected function prepareFilterSelectOptions(&$options) {
1217 foreach ($options as $value => $label) {
1218 // Recurse for optgroups.
1219 if (is_array($label)) {
1220 $this->prepareFilterSelectOptions($options[$value]);
1222 // FAPI has some special value to allow hierarchy.
1223 // @see _form_options_flatten
1224 elseif (is_object($label) && isset($label->option)) {
1225 $this->prepareFilterSelectOptions($options[$value]->option);
1228 // Cast the label to a string since it can be an object.
1229 // @see \Drupal\Core\StringTranslation\TranslatableMarkup
1230 $options[$value] = strip_tags(Html::decodeEntities((string) $label));
1236 * Tell the renderer about our exposed form. This only needs to be
1237 * overridden for particularly complex forms. And maybe not even then.
1239 * @return array|null
1240 * For standard exposed filters. An array with the following keys:
1241 * - operator: The $form key of the operator. Set to NULL if no operator.
1242 * - value: The $form key of the value. Set to NULL if no value.
1243 * - label: The label to use for this piece.
1244 * For grouped exposed filters. An array with the following keys:
1245 * - value: The $form key of the value. Set to NULL if no value.
1246 * - label: The label to use for this piece.
1248 public function exposedInfo() {
1249 if (empty($this->options['exposed'])) {
1253 if ($this->isAGroup()) {
1255 'value' => $this->options['group_info']['identifier'],
1256 'label' => $this->options['group_info']['label'],
1257 'description' => $this->options['group_info']['description'],
1262 'operator' => $this->options['expose']['operator_id'],
1263 'value' => $this->options['expose']['identifier'],
1264 'label' => $this->options['expose']['label'],
1265 'description' => $this->options['expose']['description'],
1270 * Transform the input from a grouped filter into a standard filter.
1272 * When a filter is a group, find the set of operator and values
1273 * that the chosen item represents, and inform views that a normal
1274 * filter was submitted by telling the operator and the value selected.
1276 * The param $selected_group_id is only passed when the filter uses the
1277 * checkboxes widget, and this function will be called for each item
1278 * chosen in the checkboxes.
1280 public function convertExposedInput(&$input, $selected_group_id = NULL) {
1281 if ($this->isAGroup()) {
1282 // If it is already defined the selected group, use it. Only valid
1283 // when the filter uses checkboxes for widget.
1284 if (!empty($selected_group_id)) {
1285 $selected_group = $selected_group_id;
1288 $selected_group = $input[$this->options['group_info']['identifier']];
1290 if ($selected_group == 'All' && !empty($this->options['group_info']['optional'])) {
1293 if ($selected_group != 'All' && empty($this->options['group_info']['group_items'][$selected_group])) {
1296 if (isset($selected_group) && isset($this->options['group_info']['group_items'][$selected_group])) {
1297 $input[$this->options['expose']['operator']] = $this->options['group_info']['group_items'][$selected_group]['operator'];
1299 // Value can be optional, For example for 'empty' and 'not empty' filters.
1300 if (isset($this->options['group_info']['group_items'][$selected_group]['value']) && $this->options['group_info']['group_items'][$selected_group]['value'] !== '') {
1301 $input[$this->options['expose']['identifier']] = $this->options['group_info']['group_items'][$selected_group]['value'];
1303 $this->options['expose']['use_operator'] = TRUE;
1305 $this->group_info = $input[$this->options['group_info']['identifier']];
1315 * Returns the options available for a grouped filter that users checkboxes
1316 * as widget, and therefore has to be applied several times, one per
1319 public function groupMultipleExposedInput(&$input) {
1320 if (!empty($input[$this->options['group_info']['identifier']])) {
1321 return array_filter($input[$this->options['group_info']['identifier']]);
1327 * Returns TRUE if users can select multiple groups items of a
1328 * grouped exposed filter.
1330 public function multipleExposedInput() {
1331 return $this->isAGroup() && !empty($this->options['group_info']['multiple']);
1335 * If set to remember exposed input in the session, store it there.
1336 * This function is similar to storeExposedInput but modified to
1337 * work properly when the filter is a group.
1339 public function storeGroupInput($input, $status) {
1340 if (!$this->isAGroup() || empty($this->options['group_info']['identifier'])) {
1344 if (empty($this->options['group_info']['remember'])) {
1348 // Figure out which display id is responsible for the filters, so we
1349 // know where to look for session stored values.
1350 $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
1352 // False means that we got a setting that means to recurse ourselves,
1353 // so we should erase whatever happened to be there.
1354 if ($status === FALSE && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1355 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1357 if (isset($session[$this->options['group_info']['identifier']])) {
1358 unset($session[$this->options['group_info']['identifier']]);
1362 if ($status !== FALSE) {
1363 if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1364 $_SESSION['views'][$this->view->storage->id()][$display_id] = [];
1367 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1369 $session[$this->options['group_info']['identifier']] = $input[$this->options['group_info']['identifier']];
1374 * Determines if the input from a filter should change the generated query.
1376 * @param array $input
1377 * The exposed data for this view.
1380 * TRUE if the input for this filter should be included in the view query.
1383 public function acceptExposedInput($input) {
1384 if (empty($this->options['exposed'])) {
1388 if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
1389 $this->operator = $input[$this->options['expose']['operator_id']];
1392 if (!empty($this->options['expose']['identifier'])) {
1393 $value = $input[$this->options['expose']['identifier']];
1395 // Various ways to check for the absence of non-required input.
1396 if (empty($this->options['expose']['required'])) {
1397 if (($this->operator == 'empty' || $this->operator == 'not empty') && $value === '') {
1401 if ($this->operator != 'empty' && $this->operator != 'not empty') {
1402 if ($value == 'All' || $value === []) {
1406 // If checkboxes are used to render this filter, do not include the
1407 // filter if no options are checked.
1408 if (is_array($value) && Checkboxes::detectEmptyCheckboxes($value)) {
1413 if (!empty($this->alwaysMultiple) && $value === '') {
1417 if (isset($value)) {
1418 $this->value = $value;
1419 if (empty($this->alwaysMultiple) && empty($this->options['expose']['multiple']) && !is_array($value)) {
1420 $this->value = [$value];
1431 public function storeExposedInput($input, $status) {
1432 if (empty($this->options['exposed']) || empty($this->options['expose']['identifier'])) {
1436 if (empty($this->options['expose']['remember'])) {
1440 // Check if we store exposed value for current user.
1441 $user = \Drupal::currentUser();
1442 $allowed_rids = empty($this->options['expose']['remember_roles']) ? [] : array_filter($this->options['expose']['remember_roles']);
1443 $intersect_rids = array_intersect(array_keys($allowed_rids), $user->getRoles());
1444 if (empty($intersect_rids)) {
1448 // Figure out which display id is responsible for the filters, so we
1449 // know where to look for session stored values.
1450 $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
1453 $operator = !empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']);
1455 // False means that we got a setting that means to recurse ourselves,
1456 // so we should erase whatever happened to be there.
1457 if (!$status && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1458 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1459 if ($operator && isset($session[$this->options['expose']['operator_id']])) {
1460 unset($session[$this->options['expose']['operator_id']]);
1463 if (isset($session[$this->options['expose']['identifier']])) {
1464 unset($session[$this->options['expose']['identifier']]);
1469 if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1470 $_SESSION['views'][$this->view->storage->id()][$display_id] = [];
1473 $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1475 if ($operator && isset($input[$this->options['expose']['operator_id']])) {
1476 $session[$this->options['expose']['operator_id']] = $input[$this->options['expose']['operator_id']];
1479 $session[$this->options['expose']['identifier']] = $input[$this->options['expose']['identifier']];
1484 * Add this filter to the query.
1486 * Due to the nature of fapi, the value and the operator have an unintended
1487 * level of indirection. You will find them in $this->operator
1488 * and $this->value respectively.
1490 public function query() {
1491 $this->ensureMyTable();
1492 $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", $this->value, $this->operator);
1496 * Can this filter be used in OR groups?
1498 * Some filters have complicated where clauses that cannot be easily used
1499 * with OR groups. Some filters must also use HAVING which also makes
1500 * them not groupable. These filters will end up in a special group
1501 * if OR grouping is in use.
1505 public function canGroup() {
1512 public function getCacheMaxAge() {
1513 return Cache::PERMANENT;
1519 public function getCacheContexts() {
1520 $cache_contexts = [];
1521 // An exposed filter allows the user to change a view's filters. They accept
1522 // input from GET parameters, which are part of the URL. Hence a view with
1523 // an exposed filter is cacheable per URL.
1524 if ($this->isExposed()) {
1525 $cache_contexts[] = 'url';
1527 return $cache_contexts;
1533 public function getCacheTags() {
1540 public function validate() {
1541 if (!empty($this->options['exposed']) && $error = $this->validateIdentifier($this->options['expose']['identifier'])) {
1547 * Filter by no empty values, though allow the use of (string) "0".
1549 * @param string $var
1550 * The variable to evaluate.
1553 * TRUE if the value is equal to an empty string, FALSE otherwise.
1555 protected static function arrayFilterZero($var) {
1559 return trim($var) != '';