Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Modify views filter query with hook_hook_views_query_alter

Parent Feed: 

If you are familiar with Drupal Views, you might have come across a very nifty feature called exposed filters. If you expose one of the fields as a filter then views provides a widget and a search option, where the exposed field can be searched. There is good video to learn about filter here.

However, we needed to extend the functionality so all the fields of the content type are exposed as  ‘searchable’ fields, not just the exposed fields. If we expose every fields explicitly, then the views filter will create a textbox for each field, which is not pretty. So in our example, we wanted to search ‘Person’ content type. And if the user entered either the first name, last name, address, of any of the values for the fields in the Person content type, a result would be returned.

In order to do this, we extended the hook_views_query_alter (&$view, &$query)

if ($view->name == 'people_list') {

if (startsWith($query->where[0]['clauses'][0], 'search_index.word')) {

$query->where[0]['clauses'][0] = "search_index.word LIKE '%s'";

$query->where[0]['args'][0] = '%' . $query->where[0]['args'][0] . '%';

}

}

Essentially we are modifying the where clause of the query to search with LIKE %<search term>% which will search across all the fields in the content type.

This simple extension of the hook will enable us to search across all the fields of the content type, in addition to the one that is exposed.

In addition to the code above, in the view we also have to add the ‘ Search: Search Terms ‘ as the exposed field in the filter. This step makes sure that the view uses the Drupal search as the search and filter the content type.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web