Hi,

I have a view which will always only display one node as a result. Is there any way of redirecting the view to that result's node view?

e.g. I have a view at page .com/?q=getnextwork
When you visit that page it returns one result, which is filtered by content type and has no flags.

What I need to do is to redirect the user to .com/?q=node/X. Where X is the one result which that view has identified.

This sounds really simple so I think I'm missing something obvious.
Any help would be greatly appreciated!

Many thanks,

Ben

Comments

agoradesign’s picture

Hi,
today I had to solve the same problem. I've accomplished that with a few lines:

You only need to create a custom module and implement the hook_views_post_execute hook similar to this:

function YOURMODULENAME_views_post_execute(&$view) {
  if ($view->name == 'locationsearch' && !empty($view->result)) {
    drupal_goto('node/' . $view->result[0]->nid);
  }
}

Short explanation:
I needed that feature for a view named 'locationsearch' - therefore I checked the view's name in the if condition. Further I've checked that the views's result is not empty. As my view uses node display as row plugin, my result already contains a node with its nid. If you want to use field display instead, then you have to ensure that you include the nid as field (as only field, as further info is not needed for redirection) and fetch this info in a similar way.
As last step I'm using drupal_goto command to redirect to the node's detail page (node/NID as path)

uncoolbob’s picture

I have just found that the following works great if pasted into a Global Text Area Header for a view (for example the Taxonomy Term (Content) view that ships with Drupal 7 (you have to enable it).

The tests on $view->preview stop it breaking the AJAX preview in the view edit page.

No need for templates or modules!

<?php
$view = views_get_current_view();
if (!(isset($view->preview) && $view->preview) && count($view->result)==1) {
  drupal_goto('node/' . $view->result[0]->nid);
}
?>

I guess another check that the view is a page view would be useful (you wouldn't want this happening for block views!!)

merlinofchaos’s picture

Status: Active » Fixed

Using PHP embedded in a view is a functional solution but not recommended.

Views has no built in mechanisms with which to do a redirect.

Page Manager does have a mechanism to do a redirect. It's a little bit complicated, but you can create your view with a Context display, and use the Redirect variant to redirect to the right node. You'll probably need to use the Node from View relationship to do it, using the %node:nid token from the node context. As I said this is a bit complex so expect to have to fiddle with it a bit before you find the right options, but it will enable you to do exactly what you want with no code required.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.