W3cubDocs

/Drupal 8

function hook_views_query_alter

hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query)

Alter the query before it is executed.

Parameters

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

QueryPluginBase $query: The query plugin object for the query.

See also

hook_views_query_substitutions()

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

Related topics

Hooks
Define functions that alter the behavior of Drupal core.

File

core/modules/views/views.api.php, line 874
Describes hooks and plugins provided by the Views module.

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, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_query_alter/8.1.x