Drupal 6: Display Full Node When Only One Node in a View is Returned
It is common practice when developing applications to display all the fields of a database record when returning a list of rows but the row count is only one. In Drupal Views parlance, you would want to list the output of the view IF there was more than one row, but if there is exactly one row it would be better to display the node page instead.
I've not found a way of doing this automatically in Views, so decided to do it myself with a small amount of theming.
Firstly, we are going to need the node id (nid) of each node in the view for this to work. So you need to add this to the fields section of each view you feel you want to do this for. In my example I am showing my technology_blog view in the image below.
Views: Set NID
When you add the nid field, don't forget to exclude it from the display - as shown where I've ringed the checkbox.
Now we move on to theming. I want my solution to only work for my site's theme, beezee, but to work on all my views. So I will need to create a new template file, but which one? This is where Views is your friend - if you click on Theme Information (as ringed below) you will see the default theming information. The one we are interested in is under Display Output, and we need to select the correct template file for the scope we need. I want it to work on only my beezee theme but for all views, so the correct template for me is views-view.tpl.php.
Views: Get Template Filename
This file needs to be copied to my beezee views directory. You will need to create this directory if it doesn't already exist; it does for me because of earlier tutorials.
$ cp sites/all/modules/views/theme/views-view.tpl.php sites/all/themes/beezee/views/.The copied file now needs to be edited with your favourite editor. Add the following code straight after the comment block at the beginning of the file.
<?php
global $pager_total_items, $pager_total;
if ($pager_total_items[0] * $pager_total[0] == 1)
drupal_goto('node/' . $view->result[0]->nid);
?>Ok, so what does this code do? By specifying global $page_total_items and $pager_total, these global variables become available to use in our code. The first, $page_total_items, gives the total number of items per pager. The second, $pager_total, gives the total number of pages per pager. So by multiplying the two together and checking whether the value is one, we'll know if this item is the first item of only one.
If it is, then redirect the page to the node/nid address. So that is why we added the nid to the view - so we could use the value here for the redirect. Ok! That's it!