Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughHide Block if no Results are Returned using Views in Drupal
Don’t forget to subscribe to our YouTube channel to stay up-to-date.
Creating a block using views is pretty straightforward. You could create a block to display a list of published articles or ones that have been promoted to the front page. Then you can add that block into any theme region.
But you may encounter a situation where you no longer have any articles which are published and then you end up with an empty block.
Views comes with a feature that allows you to hide a block if no results are returned and this is what will be covered in this tutorial.
Drupal Views Series
Getting Started with a Simple Example
We need to display a block that lists all articles that have been promoted to the front page. This can easily be achieved by using a custom views block
The views configuration will look something similar to the following:
This is a block created from views, and we can place the block on the sidebar, like the following:
The criteria of the views setting is based on some articles having the ‘Promoted to front page’ option checked.
The Problem
However, sometimes articles may not be promoted at all. As a result, there are no results returned from the views setup above, and the block will look like this:
How to Fix It
To avoid this situation, we can choose to Hide the Block when no results are returned. In fact, there is an option of ‘Hide block if the view output is empty’ at the bottom corner of the views setting, which a lot of people might easily overlook.
Simply enable this option, and it is done.
With this option enabled, the block will disappear when the view returns no results, like the image below:
Summary
This ‘Hide block if the view output is empty’ option is actually one which is very useful, but it can be easily overlooked.
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web