[Drupal] How to Alter Views query in Drupal 7

| | 1 min read

Altering a query is to change the results as desired by the user. hook__views_query_alter() in Drupal is for altering the query. Before start reading, you should have an idea about what is a view and how views created? See here.

Understanding hook_views_query_alter().

This hook function, the query for the views content result could be altered before it execute, we can get the query value in $view->query.

The sample code for hook_views_query_alter() :


/**
  * Implements hook_views_query_alter().
  * @param 
  *    type $view
  * @param 
  *    type $query
  */
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'myview') {
    dpm($view->query); //Displays the query for the view named 'myview'.
    dpm($view->query->where); //Displays the where condition part values in the query.
    dpm($view->query->orderby); //Displays the orderby part values in the query.
  }
}

Please see how to create views exposed form in Drupal 7, for getting complete idea.