drupal 9 modify a views query

Solutions on MaxInterview for drupal 9 modify a views query by the best coders in the world

showing results for - "drupal 9 modify a views query"
Amethyst
15 Sep 2019
1function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
2
3  // (Example assuming a view with an exposed filter on node title.)
4  // If the input for the title filter is a positive integer, filter against
5  // node ID instead of node title.
6  if ($view
7    ->id() == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
8
9    // Traverse through the 'where' part of the query.
10    foreach ($query->where as &$condition_group) {
11      foreach ($condition_group['conditions'] as &$condition) {
12
13        // If this is the part of the query filtering on title, change the
14        // condition to filter on node ID.
15        if ($condition['field'] == 'node.title') {
16          $condition = [
17            'field' => 'node.nid',
18            'value' => $view->exposed_raw_input['title'],
19            'operator' => '=',
20          ];
21        }
22      }
23    }
24  }
25}