We have a custom view, myview
, that has two exposed filters: country
and category
. For the country
value we have a value that we want to be applied regardless of what is selected as the exposed filter that is not All Countries
.
How would we alter the query after a value is selected so that we always append an or country = United States of America
to whatever value is selected for the view's query?
Goal:
After the exposed filter has been applied, alter the query such that it will return whatever the user selected AND all other nodes where country = 'United States'
.
Country value:
- All Countries
- Worldwide
- United States of America
- United Kingdom
- France
- Germany
What we were thinking of using hook_views_query_alter, but not sure how we can alter the query after a value has been selected.
mymodule.module
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
/**
* Implements hook_views_query_alter().
*/
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'myview') {
$or_statement = new Condition('OR');
$or_statement->condition('field_country', '12', '=');
$query->addWhere(0, $or_statement);
}
}
Current filters:
- published = yes
- content type = article
- country (exposed filter, display all, single select)
- category (exposed filter, display all, single select)
When using ksm()
to print the $condition_group
, this is the results. It is not even showing the two exposed filters.
Current Where Clause
10
is the value selected by the user from the exposed filter and 12
is the one we want to add.
WHERE (((node__field_country.field_country_target_id = '10')) AND (node__field_country.field_country_target_id = '12'))
Desired where clause
WHERE (((node__field_country.field_country_target_id = '10')) OR (node__field_country.field_country_target_id = '12'))