12.14.1. Переопределение Drupal views фильтра
В прошлой статье мы рассмотрели как писать интеграцию кастомной таблицы БД с модулем Views для модуля Did this help:
https://www.drupal.org/project/did_this_help
В этой статье мы изменим фильтр для поля "choice" (поле yes/no):

Сейчас это обычное текстовое поле представленное с помощью handler'а "string", куда нужно вставить строку для поиска. Но у нас есть только два варианта yes/no, так что здесь лучше иметь выбор из списка, чем поле для написания своего текста. Давайте создадим файл /did_this_help/src/Plugin/views/filter/DidThisHelp.php:
<?php
namespace Drupal\did_this_help\Plugin\views\filter;
use Drupal\views\Plugin\views\filter\InOperator;
/**
* Filters by given list of yes/no options.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("did_this_help")
*/
class DidThisHelp extends InOperator {
}
Мы будем наследоваться от класса InOperator, предоставляющего фильтр в виде выбора dropbox, radio buttons или checkboxes, в зависимости от настроек выбранных во Views UI.
В методе getValueOptions() мы добавим список доступных элементов выбора:
/**
* {@inheritdoc}
*/
public function getValueOptions() {
if (isset($this->valueOptions)) {
return $this->valueOptions;
}
$this->valueOptions = [
'yes' => $this->t('Yes'),
'no' => $this->t('No'),
];
return $this->valueOptions;
}
Свойство valueOptions определено в родительском классе InOperator, нам нужно только определить массив доступных значений.
В результате у нас будет такой доступный фильтр:

Если включить exposed filter, тогда виджет будет выглядеть как dropbox:

Вы можете переопредлить любой другой класс фильтра из списка доступных в модуле Views:
| Name | Location | Description |
|---|---|---|
| Access | core/ |
Filter by node_access records. |
| BooleanOperator | core/ |
Simple filter to handle matching of boolean values |
| BooleanOperatorString | core/ |
Simple filter to handle matching of boolean values. |
| Broken | core/ |
A special handler to take the place of missing or broken handlers. |
| Bundle | core/ |
Filter class which allows filtering by entity bundles. |
| Current | core/ |
Filter handler for the current user. |
| Date | core/ |
Date/time views filter. |
| Date | core/ |
Filter to handle dates stored as a timestamp. |
| Equality | core/ |
Simple filter to handle equal to / not equal to filters |
| FilterBooleanOperatorDefaultTest | core/ |
Filter to test queryOpBoolean() with default operator. |
| FilterPluginBase | core/ |
Base class for Views filters handler plugins. |
| GroupByNumeric | core/ |
Simple filter to handle greater than/less than filters |
| HistoryUserTimestamp | core/ |
Filter for new content. |
| InOperator | core/ |
Simple filter to handle matching of multiple options selectable via checkboxes |
| LanguageFilter | core/ |
Provides filtering by language. |
| LatestRevision | core/ |
Filter to show only the latest revision of an entity. |
| ListField | core/ |
Filter handler which uses list-fields as options. |
| ManyToOne | core/ |
Complex filter to handle filtering for many to one relationships, such as terms (many terms per node) or roles (many roles per user). |
| ModerationStateFilter | core/ |
Provides a filter for the moderation state of an entity. |
| Name | core/ |
Filter handler for usernames. |
| NodeComment | core/ |
Filter based on comment node status. |
| NumericFilter | core/ |
Simple filter to handle greater than/less than filters |
| Permissions | core/ |
Filter handler for user roles. |
| Roles | core/ |
Filter handler for user roles. |
| Search | core/ |
Filter handler for search keywords. |
| Standard | core/ |
Default implementation of the base filter plugin. |
| StatisticsLastUpdated | core/ |
Filter handler for the newer of last comment / node updated. |
| Status | core/ |
Filter by file status. |
| Status | core/ |
Filter by published status. |
| StringFilter | core/ |
Basic textfield filter to handle string filtering commands including equality, like, not like, etc. |
| TaxonomyIndexTid | core/ |
Filter by term id. |
| TaxonomyIndexTidDepth | core/ |
Filter handler for taxonomy terms with depth. |
| UidRevision | core/ |
Filter handler to check for revisions a certain user has created. |
| UserUid | core/ |
Filter handler to accept a user id to check for nodes that user posted or commented on. |
| UserUid | core/ |
UID filter to check for nodes that a user posted or commented on. |
| ViewsFilter | core/ |
Defines a Plugin annotation object for views filter handlers. |