3

I have a view that shows a list of nodes and has a contextual filter. If the number of nodes shown is only 1 then I want to redirect to that node page instead of showing the view. Can I do that in views or do I have to code it?

1

1 Answer 1

6

I don't think Views does anything like that by default, but a quick...

if (count($view->result)==1) {
  drupal_goto('node/' . $view->result[0]->nid);
}

...at the beginning of a display output template for the view in question should do it for you.

Or better yet, per @MPD...

function MOTOMODULE_views_pre_render(&$view) {

  if ($view->name=='JUSTONEPLEASE' && count($view->result)==1) {
    drupal_goto('node/' . $view->result[0]->nid);
  } 

  // any other pre_render()ing here

}
4
  • great idea. I wonder if I could use a views_php field for that as well.
    – uwe
    Commented Jul 20, 2012 at 19:41
  • Dunno :) Check it out and let us know. I tend to think if it works it to be a matter of personal preference; I like to use templates so I can quickly look at them without going into UIs and such and thus I shy away from php fields that are in the DB.
    – Jimajamma
    Commented Jul 20, 2012 at 19:47
  • 2
    Do it from a view hook. Try hook_views_pre_render
    – mpdonadio
    Commented Jul 20, 2012 at 22:14
  • D'oh! I keep on forgetting about that bad boy. Definitely the right call.
    – Jimajamma
    Commented Jul 21, 2012 at 1:27

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.