function hook_views_query_alter

Same name and namespace in other branches
  1. 9 core/modules/views/views.api.php \hook_views_query_alter()
  2. 8.9.x core/modules/views/views.api.php \hook_views_query_alter()
  3. 11.x core/modules/views/views.api.php \hook_views_query_alter()

Alter the query before it is executed.

Parameters

\Drupal\views\ViewExecutable $view: The view object about to be processed.

\Drupal\views\Plugin\views\query\QueryPluginBase $query: The query plugin object for the query.

See also

hook_views_query_substitutions()

\Drupal\views\Plugin\views\query\Sql

Related topics

6 functions implement hook_views_query_alter()

Note: the procedural functions in this list are found by pattern matching, so the list may include some functions that are not actually implementations of this hook.

ContentModerationTestViewsHooks::viewsQueryAlter in core/modules/content_moderation/tests/modules/content_moderation_test_views/src/Hook/ContentModerationTestViewsHooks.php
Implements hook_views_query_alter().
content_moderation_test_views_views_query_alter in core/modules/content_moderation/tests/modules/content_moderation_test_views/content_moderation_test_views.module
Implements hook_views_query_alter().
ViewsOperations::viewsQueryAlter in core/modules/workspaces/src/Hook/ViewsOperations.php
Implements hook_views_query_alter().
ViewsTestDataViewsExecutionHooks::viewsQueryAlter in core/modules/views/tests/modules/views_test_data/src/Hook/ViewsTestDataViewsExecutionHooks.php
Implements hook_views_query_alter().
views_test_data_views_query_alter in core/modules/views/tests/modules/views_test_data/views_test_data.views_execution.inc
Implements hook_views_query_alter().

... See full list

1 invocation of hook_views_query_alter()
Sql::alter in core/modules/views/src/Plugin/views/query/Sql.php
Let modules modify the query just prior to finalizing it.

File

core/modules/views/views.api.php, line 894

Code

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->id() == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, change the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = [
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          ];
        }
      }
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.