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
1. Getting Started with Views in Drupal
2. Create Infinite Scroll pages using Views Infinite Scroll in Drupal
3. Hide Block if no Results are Returned using Views in Drupal
4. Bulk Update Content using Views Bulk Operations in Drupal
5. Add Custom Tab to User Profile Page with Views in Drupal
6. Conditionally Display View Fields using Views Conditional in Drupal
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.
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:
This ‘Hide block if the view output is empty’ option is actually one which is very useful, but it can be easily overlooked.