- 157 views
Use HOOK_views_query_alter()
At this point you have no other option than to create custom module, so I will not go through the process at all. Just use this hook like that:
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
...
}
Add relationship to the fields you need to filter on
Adding relationship in Views is complete different way. Views API is optimised to always prefer / add LEFT JOINs over anything else (it is because some sql systems does not support RIGHT JOINs) so just use the code below:
// Add LEFT JOIN to First Field
$configuration = [
'table' => 'node__field_YOUR_FIELD_NAME',
'field' => 'entity_id',
'left_table' => 'node_field_data',
'left_field' => 'nid'
];
$join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $configuration);
$query->addRelationship('node__field_YOUR_FIELD_NAME', $join, 'node_field_data');
Use addWhereExpression method from QueryPluginBase class
This is really not well documented in Drupal API docs but you can write whatever you see fit into addWhereExpression and it will run. So use the code below:
$queryExpression = "
(
(node__field_YOUR_FIELD_NAME.field_YOUR_FIELD_NAME_value IN('1'))
AND
(node__field_SECOND_FIELD_NAME.field_SECOND_FIELD_NAME_value IN('2'))
)
OR
(
node__field_SECOND_FIELD_NAME.field_SECOND_FIELD_NAME_value IN('3')
)
";
$group_id = $query->setWhereGroup('AND');
$query->addWhereExpression($group_id, $queryExpression);
Full code!
I mean, you probably get the glimpse of how it works, but here is the full code for you if you do not like snipplets above.
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'YOUR_VIEW_ID') {
// Add LEFT JOIN to First Field
$configuration = [
'table' => 'node__field_YOUR_FIELD_NAME',
'field' => 'entity_id',
'left_table' => 'node_field_data',
'left_field' => 'nid'
];
$join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $configuration);
$query->addRelationship('node__field_YOUR_FIELD_NAME', $join, 'node_field_data');
// Here you can add LEFT JOIN to second field...
/*
* VIEWS ALTER LAYOUT:
*
- Exposed Filters -
AND
(
(
Field 1 = Value 1 AND
Field 2 = Value 2
)
OR
(
Field 2 = Value 3
)
)
*/
// Here you basicly write whatever will run inside WHERE clause in query
$queryExpression = "
(
(node__field_YOUR_FIELD_NAME.field_YOUR_FIELD_NAME_value IN('1'))
AND
(node__field_SECOND_FIELD_NAME.field_SECOND_FIELD_NAME_value IN('2'))
)
OR
(
node__field_SECOND_FIELD_NAME.field_SECOND_FIELD_NAME_value IN('3')
)
";
$group_id = $query->setWhereGroup('AND');
$query->addWhereExpression($group_id, $queryExpression);
}
}