Modify views filter query with hook_hook_views_query_alter

18 Dec

Modify views filter query with hook_hook_views_query_alter

in Drupal, Drupal Planet, Drupal Planet, exposed filter, exposed filter, search, search, views, views

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.

copyright 2012 10jumps Llc.

copyright 2012 10jumps LLC.