Last active
March 18, 2020 14:52
-
-
Save devkinetic/02439eff676d0ad89a558e0b2693b9e8 to your computer and use it in GitHub Desktop.
Drupal 8 Contextual Filter IS NULL via hook_views_query_alter()
This file contains hidden or 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
<?php | |
use Drupal\views\ViewExecutable; | |
use Drupal\views\Plugin\views\query\QueryPluginBase; | |
/** | |
* Implements hook_views_query_alter(). | |
* | |
* @param ViewExecutable $view | |
* @param QueryPluginBase $query | |
*/ | |
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) { | |
// apply this to all group event views | |
if (strpos($view->id(),'group_event') !== false) { | |
cp_event_views_contextual_is_null($query); | |
} | |
} | |
/** | |
* Convert queries using our special 'null' value in contextual filters into 'IS NULL' clauses | |
* | |
* How to use: | |
* - Add a contextual filter | |
* - Set a default value of 'null' | |
* | |
* @param QueryPluginBase $query | |
*/ | |
function cp_event_views_contextual_is_null(QueryPluginBase &$query) { | |
// loop over where groups | |
if (is_array($query->where)) { | |
foreach ($query->where as $whereIndex => $where) { | |
// loop over where group conditions | |
if (is_array($where['conditions'])) { | |
foreach ($where['conditions'] as $conditionIndex => $condition) { | |
// loop over group condition values | |
if (is_array($condition['value'])) { | |
foreach ($condition['value'] as $valueIndex => $value) { | |
// if the value is the string of 'null' | |
if ($value === 'null') { | |
// convert the condition to a 'IS NULL' query | |
$query->where[$whereIndex]['conditions'][$conditionIndex]['field'] = strstr($condition['field'], ' =', true); | |
$query->where[$whereIndex]['conditions'][$conditionIndex]['value'] = NULL; | |
$query->where[$whereIndex]['conditions'][$conditionIndex]['operator'] = 'IS NULL'; | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
/** | |
* Source: | |
* https://www.chapterthree.com/blog/using-hook-views-query-alter | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment