[Snippet] Pass multiple filter values in Drupal Views

One the most powerful function in Drupal Views is contextal filter. This function able to the Views module to filter the result based on argument specific in contextual filter item. However, the problem with this function is it unable to support multiple filter by "OR" conditions. The best solution to counter this problem is by altering its query before Views rendering the results.

By creating custom module, we leveraging hook_views_query_alter().

function my_module_views_query_alter(&$view, &$query) {
  dpm($query,'query');
}

This will shows all query that available in all views. So, we specific by add condition to target specific views.

if ($view->current_display == 'my_current_display') { ... }

Then, by adding query altering for an array:

foreach ($nids as $nid){
  $query->where[1]['conditions'][] = array(
   'field' => 'node.nid',
   'value' => $nid,
   'operator' => '=',
 );

After that we add some more query altering:

$query->where[1]['type'] = 'OR';

Save and clear your cache.

Kategori