Creating A Custom Exposed View Filter In Drupal 8 To Use With Workflow States

Tags: Drupal 8



Creating workflow states with the workflow module and attaching them to entities is quite simple. Example, the transitions “draft”, “editing”, “published” for the story node type. I’m not sure about Drupal 7, but in Drupal 8, adding filters to workflow enabled nodes and filtering by them is a little tricky. The filter does appear when you are adding in the filter, but the widget is displayed in an odd way (with workflow description textarea). The solution is to create a custom filter. In this example, I'll create a phase filter where a workflow state is considered a phase of the node.

To create a new filter, you have to first define it in the hook_views_data_alter(). Insert the following piece of code in your custom_module.module file:

After that is done, clear cache and search for the filter in the view. You will see the label ‘Phase filter’, although selecting it won’t do anything because we haven’t defined it yet. That is the next step. In the custom module, create a file ‘PhaseViewsFilter.php’ in the folder Plugin/views/filter with the following code:

In the above code, we are extending the ManytoOne class to be able to add relationship and add multiple selections in the filter once exposed.

Now you can clear cache again and add the filter in the view, and even expose it.

Abhai Sasidharan, Back-end Developer
Posted by

Abhai Sasidharan, Back-end Developer

Off work, you might find him on the archery range or playing his ukulele. He also enjoys cooking, photography, and practicing his rainbow kick on the soccer field.