blog-banner

Clear views cache when insert, update, delete node in Drupal 7

  • Cache
  • Drupal
  • Drupal Planet
  • Views

Clear Views Cache in Drupal

This blog describes how to clear views cache while inserting, updating, and deleting a node. If we want to improve site performance, then views caching is one of the options.

For example, let's consider that there is a view that displays a list of records, and it will be updated occasionally. Then we can render views data from a cache rather than a server by setting up a cache for views. We can set views cache at an Advanced section of its settings page. Drupal supports time-based caching by default. We can cache the views in 6 days. If you want to cache the views over 6 days, then you could select the 'Custom' option and fill a number of seconds in the 'Seconds' textbox.

Drupal 7: Clear views cache

Suppose you have cached views for 30 mins. Then it won't display updated data until 30 mins, even if a new node is added to that views. It displays updated data only after 30 mins because the views are cached for 30 mins. In that situation, the user can't view new data in cached views. So we need to clear views cache when we add a new node. Then only we can see new data in views and also data is rendered from a cache.

Let's see how to clear views cache while inserting the node:

 <?php
 /**
  * Imeplement hook_node_insert().
  */
 function kf_node_insert($node) {
   if ($node->type == 'tasks') {
     //clear views cache
     $viewsname = 'activity';
     cache_clear_all('ctools_export:views_view:' . $viewsname, 'cache_views', TRUE);
     cache_clear_all($viewsname, 'cache_views_data', TRUE);
   }
 }

Similarly, you can clear views cache when updating or deleting a node using hook_node_update() and hook_node_delete() respectively. Now you could see the performance of the views page will be increased.

Get awesome tech content in your inbox