Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

12.14.1. Переопределение Drupal views фильтра

03/11/2020, by Ivan

В прошлой статье мы рассмотрели как писать интеграцию кастомной таблицы БД с модулем Views для модуля Did this help:

https://www.drupal.org/project/did_this_help

В этой статье мы изменим фильтр для поля "choice" (поле yes/no):

Yes/no field

Сейчас это обычное текстовое поле представленное с помощью 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, нам нужно только определить массив доступных значений.

В результате у нас будет такой доступный фильтр:

Yes/No filter

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

Yes/No dropdown

Вы можете переопредлить любой другой класс фильтра из списка доступных в модуле Views:

Name Location Description
Access core/modules/node/src/Plugin/views/filter/Access.php Filter by node_access records.
BooleanOperator core/modules/views/src/Plugin/views/filter/BooleanOperator.php Simple filter to handle matching of boolean values
BooleanOperatorString core/modules/views/src/Plugin/views/filter/BooleanOperatorString.php Simple filter to handle matching of boolean values.
Broken core/modules/views/src/Plugin/views/filter/Broken.php A special handler to take the place of missing or broken handlers.
Bundle core/modules/views/src/Plugin/views/filter/Bundle.php Filter class which allows filtering by entity bundles.
Current core/modules/user/src/Plugin/views/filter/Current.php Filter handler for the current user.
Date core/modules/datetime/src/Plugin/views/filter/Date.php Date/time views filter.
Date core/modules/views/src/Plugin/views/filter/Date.php Filter to handle dates stored as a timestamp.
Equality core/modules/views/src/Plugin/views/filter/Equality.php Simple filter to handle equal to / not equal to filters
FilterBooleanOperatorDefaultTest core/modules/views/tests/modules/views_test_data/src/Plugin/views/filter/FilterBooleanOperatorDefaultTest.php Filter to test queryOpBoolean() with default operator.
FilterPluginBase core/modules/views/src/Plugin/views/filter/FilterPluginBase.php Base class for Views filters handler plugins.
GroupByNumeric core/modules/views/src/Plugin/views/filter/GroupByNumeric.php Simple filter to handle greater than/less than filters
HistoryUserTimestamp core/modules/history/src/Plugin/views/filter/HistoryUserTimestamp.php Filter for new content.
InOperator core/modules/views/src/Plugin/views/filter/InOperator.php Simple filter to handle matching of multiple options selectable via checkboxes
LanguageFilter core/modules/views/src/Plugin/views/filter/LanguageFilter.php Provides filtering by language.
LatestRevision core/modules/views/src/Plugin/views/filter/LatestRevision.php Filter to show only the latest revision of an entity.
ListField core/modules/options/src/Plugin/views/filter/ListField.php Filter handler which uses list-fields as options.
ManyToOne core/modules/views/src/Plugin/views/filter/ManyToOne.php 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/modules/content_moderation/src/Plugin/views/filter/ModerationStateFilter.php Provides a filter for the moderation state of an entity.
Name core/modules/user/src/Plugin/views/filter/Name.php Filter handler for usernames.
NodeComment core/modules/comment/src/Plugin/views/filter/NodeComment.php Filter based on comment node status.
NumericFilter core/modules/views/src/Plugin/views/filter/NumericFilter.php Simple filter to handle greater than/less than filters
Permissions core/modules/user/src/Plugin/views/filter/Permissions.php Filter handler for user roles.
Roles core/modules/user/src/Plugin/views/filter/Roles.php Filter handler for user roles.
Search core/modules/search/src/Plugin/views/filter/Search.php Filter handler for search keywords.
Standard core/modules/views/src/Plugin/views/filter/Standard.php Default implementation of the base filter plugin.
StatisticsLastUpdated core/modules/comment/src/Plugin/views/filter/StatisticsLastUpdated.php Filter handler for the newer of last comment / node updated.
Status core/modules/file/src/Plugin/views/filter/Status.php Filter by file status.
Status core/modules/node/src/Plugin/views/filter/Status.php Filter by published status.
StringFilter core/modules/views/src/Plugin/views/filter/StringFilter.php Basic textfield filter to handle string filtering commands including equality, like, not like, etc.
TaxonomyIndexTid core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTid.php Filter by term id.
TaxonomyIndexTidDepth core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTidDepth.php Filter handler for taxonomy terms with depth.
UidRevision core/modules/node/src/Plugin/views/filter/UidRevision.php Filter handler to check for revisions a certain user has created.
UserUid core/modules/comment/src/Plugin/views/filter/UserUid.php Filter handler to accept a user id to check for nodes that user posted or commented on.
UserUid core/modules/tracker/src/Plugin/views/filter/UserUid.php UID filter to check for nodes that a user posted or commented on.
ViewsFilter core/modules/views/src/Annotation/ViewsFilter.php Defines a Plugin annotation object for views filter handlers.