6

If you want to clear cache on a render array when any node is updated you can add as a cache_tag, "node_list":

  '#cache' => [
    'tags' => ['node_list']
  ],

But there isn't a way to do this when only nodes of a certain bundle are added or updated.

If you have a block, for example, and you'd like to clear the cache on it when any node with bundle "article" is added or updated, how would you do this?

13

You can easily create a custom cache tag related to properties on nodes by invalidating it yourself.

Based on this article: https://www.drupal.org/project/views_custom_cache_tag

I created a custom tag for each node type, that is invalidated on node update:

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_node_presave(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function mymodule_node_delete(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

Then in my build array for my block I added:

$build['#cache'] = [
  'tags' => [
    'node_type:article',
    'node_type:video'
  ],
];

This means this block will only refresh when nodes that are of type "article" or "video" are created or updated.

You could do the same process for any property on an entity, not just bundle. For example, if you want a list of nodes to stay cached unless the nodes within it change their url alias, you could add code that checks if the url aliases is changing and then invalidate your tag node:123:url_alias".

| improve this answer | |
  • Curious why you chose to do the clearing in a presave instead of an after save? – Brian Apr 14 '17 at 13:31
  • presave works on both insert and update. If you use the after save hooks, you have two you'd have to use: hook_entity_insert and hook_entity_update or hook_ENTITY_TYPE_insert and hook_ENTITY_TYPE_update – oknate Nov 8 '17 at 17:18
  • Cache tags by entity type AND bundle might be added to core : drupal.org/project/drupal/issues/2145751 – Philipp Michael Nov 30 '17 at 10:47
  • Hey @oknate, do you have any update to your solution ? i tried to implement it, but it's not working anymore for me. Cheers, – lchabrand Jan 28 at 21:02
1

For others with this same question to have cache tags based on bundle, there is a “handy” module Handy Cache Tags which works really well. https://www.drupal.org/project/handy_cache_tags

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.