How To Make A Custom Views Filter Dropdown Plugin In Drupal 9
Table of contents
Sometimes the available View filters are insufficient to meet a developer’s needs. I faced a similar problem in a Drupal 9 site in which a basic personalization form was used.
Within this form, I needed to read the value of a session variable containing the taxonomy term id (tid). After that, the next step was to produce the title of all those nodes having that taxonomy term id as a dropdown exposed to the users.
The options were tailored according to the region of the user. This was not available from the default filters. As a solution, a customer filter was required. And this process of creating a custom Drupal 9 views filter was done in two steps.
Step 1: Create A Plugin
Create a folder src/Plugins/views/filter in a custom module and create the filter class name MyCustomViewsFilter. Make sure this class extends the ManytoOne class. Note: This code has utilized Dependency Injection for calling services like temp store factory and Entity type manager. It is not necessary to implement the ContainerFactoryPluginInterface unless the developer is trying to insert a Dependency Injection within the filter. But one should remember that it is a good practice to use Dependency Injection to call other classes.
<script src="https://gist.github.com/binnyaxel/c79d994d875d0ffcbd53503616f0c437.js"></script>
Three items are required to implement the Plugin filter.
- The class should extend the class ManytoOne.
- The class must have the annotation in the required format.
- The presence of standard views filter methods, init & generateOptions.
Steps 2: Exposed Plugin To Views
<script src="https://gist.github.com/binnyaxel/9bf95aa55d79f906db2e26479d7601b4.js"></script>
Once the class is ready, ensure the filter is available to all the required data types in the Views. Here, the filter is exposed to all the nodes through hook_views_data_alter. The data in the hook comes up in the Views UI when one searches for this filter.
Note: Keep in mind that the ‘node’ and ‘nid’ appear in the actual SQL query and should have valid table and column names. Do not assign any random name as it has to pass to the SQL query.
For example, the query generated by the views would be something like
SELECT * FROM ‘node’ where nid = id
This is a very simplistic view query. This is why node and nid should be the actual names of the table and column names for this to work.
Using The Filter
Once everything is set up, make sure to clear the cache. Add the new filter just like any other filter available by default.
Subscribe to my newsletter
Read articles from Binny Thomas directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by