Drupal 7 - How to Modify a Views Query with a Custom Module

Category: 

To make custom alterations, changes, adjustments, etc to a Views query in Drupal 7, try this module (or add the code in the .module and .view.inc files to your own custom module):

my_module.info

name = My Module
description = Behold my awesome module.
core = 7.x
package = Other

my_module.module

<?php

/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3, 
    'path' => drupal_get_path('module', 'my_module'), 
    'template path' => drupal_get_path('module', 'my_module'),
  );
}

my_module.views.inc

<?php

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view_machine_name' && $view->current_display == 'page') {
    drupal_set_message("I can make changes to the view here..");  
  }
}

From here, I'll typically use the Devel module's dpm function to investigate the $view and $query objects and make the necessary programmatic changes.

Be sure you use the correct machine name for the view's display. In the example above, the machine name for the Page display of my view was 'page', so in the boolean I use:

$view->current_display == 'page'

To retrieve your view's display name machine name, click on your view's display button when editing your view, then check out the URL in your address bar, it will be something like this:

admin/structure/views/view/my_view_machine_name/edit/page

In the above example, the Page display's machine name was 'page' on the view. Other examples of display machine names are: default, page_1, attachment_1, etc

Comments

For some reason I couldn't get Drupal to execute the hook_views_query_alter until I put it the function directly in my .module file.

tyler's picture

Thanks for pointing that out Dan. It's possible Views is expecting it in the .module file, since this article was posted. I'll definitely keep that in mind next time I utilize this technique and will update the article accordingly. Michigan Drupal!

tyler's picture

Just to confirm, I had to use the approach documented in this article, and it worked fine.

For others, Dan did follow up and say: "It magically started working after I deleted the include file and created a new one. Can't confirm but I probably named the first file _views.inc because the file that now works is correctly named .views.inc"

Add new comment