Last active
March 25, 2016 18:55
-
-
Save boyron/fe10c8e4571fd0d31d24 to your computer and use it in GitHub Desktop.
Drupal views: Merge contextual filter with exposed filters in query.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file: MY_MODULE.views.inc | |
* | |
* Implementation of hook_views_query_alter(). | |
* 1. Resolves conflict between contextual filter and regular filter (topic id, sub topic). | |
* Both refer to same database field, so merge them in one 'where' clause instead of two that Views comes up with. | |
* 2. By default, show all results from a topic and its sub-topics. | |
* [If a document is tagged with a sub-topic but not its parent topic, it was not shown in the default result.] | |
* @param view $view | |
* @param views_plugin_query_default $query | |
*/ | |
function MY_MODULE_views_query_alter(&$view, &$query) { | |
$topics_tid_a = array(); | |
if ($view->name == 'MY_VIEW' && $view->current_display=='default') { | |
if(count($view->exposed_raw_input) && count($view->exposed_raw_input['field_topics_tid'])) { | |
$topics_tid_a = array_merge($topics_tid_a, $view->exposed_raw_input['field_topics_tid']); | |
foreach($query->where as $k => $condition) { | |
if($k==0) continue; // first group is for contexual filters | |
foreach($condition['conditions'] as $i => $c) { | |
if(strpos($c['field'],'field_data_field_topics.field_topics_tid') !== false) { | |
unset($query->where[$k]['conditions'][$i]); | |
} | |
} | |
} | |
} else { | |
$topics_tid_a = $view->args; | |
$options = _get_available_filter_options(); | |
if(count($options['subtopic'])) { | |
$topics_tid_a = array_merge($topics_tid_a, array_keys($options['subtopic'])); | |
} | |
} | |
$query->where[0]['conditions'][0]['field'] = 'field_data_field_topics.field_topics_tid'; | |
$query->where[0]['conditions'][0]['operator'] = 'in'; | |
$query->where[0]['conditions'][0]['value'] = $topics_tid_a; | |
} | |
} | |
/** | |
* @file: MY_MODULE.module | |
* | |
* Implemented hook_views_api(). | |
* @return type | |
*/ | |
function MY_MODULE_views_api() { | |
return array( | |
'api' => 3, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was super helpful. Thank you for sharing.