Showing a different View if View is empty in Views 2 in Drupal 6

In Views 3 a useful feature was added that when you had an empty view you could show a different view instead. Unfortunately within Views UI in Drupal 6 you can only add a basic text area. You could set up a PHP filter but that could cause problems with security.

This tutorial will guide you through showing another view if the original view is empty.

You will need a custom module (may also work within your themes template.php file). We will be making use of the hook hook_views_pre_render() to add the new view to our existing view as an attachment.

The required PHP code

function MODULE_NAME_views_pre_render(&$view) {
  if (
$view->name == 'original_view_name' && $view->current_display == 'view_display_name') {
    if (empty(
$view->result)) {
$attachment views_embed_view('new_view_name''view_display_name');
$view->attachment_after $attachment;

Getting the View name and display name of your Views

You will need to get the machine name of both of your Views which can be seen on the admin/build/views page.


In the screenshot above, it is the bold bit. You will also need the display name, for all views when they are set up they have a default one which is called default, but if you add a different display type such as block or page then this will differ. In the screenshot below it is the Machine Name.


One additional step

If your View is completely empty, the attachment will be added but won't be displayed. So to make sure that the View isn't completely empty, you need to add a Global: Text area to the Empty text section of your original View.

Delete the label and leave the textarea blank (you can enter some text if you wish, this will appear above the attachment).


I heard you like views...