How to trigger contexts on Views pages

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
seanberto's picture

Hi Folks,

Curious how best to skin this cat. I'm looking to trigger a context based upon the arguments passed to a view. The view is using a page layout. The argument is a taxonomy term. The context condition is set by that taxonomy term.

Right now, I'm using a hook_views_pre_view function in a custom module. If arguments are passed to the view, I check that they represent a taxonomy term and then pass that term context_set_by_condition(). I know that there are two or three different views hooks that I could use instead of pre_view. I'm guessing that I could also write a custom argument handler in the view itself.

Thoughts? One issue that I've found with using the views hooks in a custom module:

The views hook gets called for every view on a page. I guess that's not a huge deal, but writing a condition that checks for a specific type of view before calling the context hook is a little clunky. I could hardcore the view name, but that seems fragile. Or, I could look just for views that receive arguments and are using a page display - but the $view object stores the display in a funky spot, and it just feels clunky.

Cheers,
Sean Larkin
ThinkShout.com

Comments

context_contrib, which is

jhedstrom's picture

context_contrib, which is responsible for setting contexts based on views, uses hook_views_pre_view, so if you're using that, I think you're good.

<?php
/**
* Implementation of hook_views_pre_view().
*/
function context_contrib_views_pre_view($view, $args) {
  switch (
$view->display_handler->display->display_plugin) {
    case
'page':
    case
'calendar':
     
context_set_by_condition('views', $view->name);
     
// Set any contexts associated with the current display
     
if (!empty($view->current_display)) {
       
context_set_by_condition('views', "{$view->name}:{$view->current_display}");
      }
      break;
  }
}
?>

However, if you also define a context for that view (independent of arguments passed) you may run into module weighting issues with that, since context only allows one context to be set for a given namespace/attribute combination, so whichever gets called first will be your context.

As always, you rock J

seanberto's picture

As always, you rock J Dawg.

TY,
S

Oh, and can I second Grant's

seanberto's picture

Oh, and can I second Grant's request that you present on Context at the DUG very soon?
-s