How to merge Drupal views filters

Earlier we talked about how to force Drupal views contextual filter to use logical OR condition.

Now consider the following case:

  • You have a topic (taxonomy term) page.
  • Each topic has some sub-topics (taxonomy terms under topics)
  • In the topic page, you have resource list which shows resources tagged with this topic. The list is made by a drupal view with topic set as contextual filter.
  • Now the list need a sub topics filter. Sub topics under this topic, that the list belongs to, will only shows up using views exposed filter.

The complexity here is both topic and sub topic shares the same database id (field_topics_tid) and both are set in your views contextual filter and exposed filter.

So when user chooses a sub topics filter, views query will look like

WHERE field_data_field_topics.field_topics_tid = <topic_id_from_contextual_filter> AND field_data_field_topics.field_topics_tid = <topic_id_from_resource_filter>

As you see this will not generate a valid results.

We will need to do a logical OR using IN operator like

WHERE field_data_field_topics.field_topics_tid IN (<topic_id_from_contextual_filter>, <topic_id_from_resource_filter>)

Check this code from one of my projects to see how can we achieve this using views API.

Please let me know if you have any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *