Drupal 8: Invalidate views cache (custom cache tags)
Problem
Our site has an events listing page, that displays upcoming events. The page is created using Drupal views.
The view has a filter that shows all events whose start date is greater than or equal to the current date.
In some cases the past events were appearing on the current events listing page.
This was happening because the output was getting cached due to some modules like dynamic page cache, internal page cache, etc.
Solution
We fixed this with the help of Views Custom Cache Tags module and by setting up a cron job on the server.
Steps
Install the module
Download and install https://www.drupal.org/project/views_custom_cache_tag module.
Configure the view
- Edit the view in question
- Go to ‘Advanced’ section of the view, which is at the extreme right side
- From caching section select ‘Custom Tag based’ option
- In the next step (Caching options) add the cache tag that will be invalidated on cron run
- Save the view
Write hook cron
Write a hook cron that will look something like below:
/**
* Implements hook_cron().
*/
function MODULENAME_cron() {
\Drupal\Core\Cache\Cache::invalidateTags(['my_events_page']);
}
‘my_events_page’ is the cache tag that we declared in the view.
Depending on the project requirement, have a cron job running daily or after every few hours.
On every cron run the cache of the view with the mentioned custom cache tag will be purged.
Conclusion
For site’s better performance we would usually cache most of the pages with the help of various Drupal modules. But for a few pages, like events, we would like to have the page cache be cleared after every specific time, so that the most relevant data / nodes are displayed on the page.