Score:0

Using views_query_alter() hook to dynamically add a OR "where" to a Search API View?

ng flag

We have a Search API View that we need to dynamically include results to the query that where filtered out.

The use case is that the Search Index View shows a filtered list of node but we have a checkbox to "Include National Listings" where nodes that are marked as "National" should show in the results even if the do not meet the current search or facet filters.

The below code is probably on the right track but it filters all results and produces no output:

 if ($view->id() == 'services_search_index'){

    $query->setGroupOperator('OR');
    $query->setWhereGroup('OR', 1);
    $operator = '=';
    $field = 'field_resource_location_type';
    $value = 'National';
    $query->addWhere(1, $field, $value, $operator);

  }

Here's the Views Query output with the above alter added:

Index: services
Keys: NULL
Conditions:
  field_resource_location_type = 'National'
Sorting: administrative_area ASC, title ASC
Options: array (
    'search_api_view' => 'object (Drupal\\views\\ViewExecutable)',
  )
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.