1

I currently have a unique situation whereby I need a to use a different term reference field in a view's contextual filters based on a node's content type value. I don't want to have to manually add a display for each possible combination of content types so I have been tying to use hook_views_query_alter() to accomplish what is now seeming impossible to me.

In my .module file I have:

/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() { // your module name into hook_views_api
  return array(
    'api' => 3,     
    'path' => drupal_get_path('module', 'mymodule').'/includes',
  );
}

Then in the file mymodule/includes/mymodule.views.inc:

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(&$view, &$query) {
   //this is the name of our View and Display
   if ($view->name == 'shop' && $view->current_display == 'listings') {

       $query->add_table('field_data_field_my_category');
       //then add where clause afterwards etc etc
   }
}

This throws the error:

Fatal error: Call to undefined method SelectQuery::add_table()

Which leads me to believe that the Views API is not loading properly, unless I'm completely on the wrong track here.

I've been trying to find the best practices for altering views queries but have just ended up being generally confused and frustrated. Could anyone lead me towards the light please?

2 Answers 2

2

I don't know enough about your problem to say whether using hook_views_query_alter is the best approach.

In regards to the error you're getting, the answer is in the error message: the query object you have is an instance of SelectQuery. If you look at the documentation for SelectQuery you will see that it doesn't have an add_table method.

Instead you should use SelectQuery::addJoin (or one of the more specific methods, such as SelectQuery::innerJoin, SelectQuery::leftJoin, etc.)

1
  • thanks for your reponse Alice! I think the barrage of tutorials and online resources I tried to absorb under pressure confused me. I'll have a look at the documentation links you provided and take it from there :) Commented Mar 20, 2013 at 11:26
0

Try adding $view to the line:

{$view->$query->add_table('field_data_field_my_category');}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.