How To Make A Drupal 9 Select Filter In Views Exposed Filter Dependent On Another Via AJAX

How To Make A Drupal 9 Select Filter In Views Exposed Filter Dependent On Another Via AJAX

Do you have a set of exposed filters in Drupal 9 in views as dropdowns? Do you need to dynamically make one of the filters depend on the other? The obvious solution to these problems might include using Forms Ajax in views exposed filters. But that does not work anymore due to a bug in Drupal 9 core. The option remaining is to implement the solution by using custom Ajax.

The Solution To implement the solution, follow the steps.

Step 1: Create An Asset Library Create an asset library to write Javascript. In the custom module, add the following. Create the file if it does not exist.

Note: The first line, the library's name, should be noted if it has to be added to some page.

Step 2: Create A Javascript File To Write The Ajax This step includes writing the Javascript code that will trigger the ajax to change the select list options. Once the code is written, put it in the file called my_filter_ajax inside the js folder of the custom module as mentioned in the asset library file.

Step 3: Create A Route And Controller The route and controller will act as the Ajax callback. This is where the jQuery in the previous file will post the data. The data would be the selected value of the first filter and passed to the route through the Ajax post. The ajax will be posted to the path ‘/mycustom/filter/ajax/{cat_id}’ as defined in the routing file below. Route:

The last component in the URL ‘cat_id’ is a placeholder. This placeholder will be used to accept the value of the selected item in the exposed filter and will be passed to the controller.

Note: Ensure that the permissions match the view and its use cases. To understand this better, refer to the access content example given below.

Provide an Ajax response Instead of the standard render array response. This is vital to making this work. Use the Replace Command to implement the solution. Here, an HTML select list is returned with data obtained after running a query through the database using the value selected in the filter.

Note: The constructor and create functions are optional and used only for Dependency injection. It is recommended to use these OOPs methods to call the other services/classes instead of the \Drupal::function.

Step 4: Add The Asset Library To The View

Add the asset library to the view. It can be done by adding it to the twig template. There are other ways of adding the library to the view.

Clear the cache, and you are good to go.