4

I understand how you can add cache tags to a custom query for a particular entity id (or list of them) but is there a way to add cache tags that will invalidate a query if any entity of type FOO is updated/added/deleted?

1

2 Answers 2

7

You could use the module handy_cache_tags, then you would have this type of tags:

handy_cache_tags:[entity_type]
handy_cache_tags:[entity_type]:[entity_bundle]
1

In your blockcache_examples.module file:

use Drupal\Core\Cache\Cache;
use Drupal\node\Entity\Node;

/**
 * Invalidate the custom tag if entities of type "page" get updated
 */
function blockcache_examples_node_update(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

/**
 * Invalidate the custom tag if entities of type "page" get inserted
 */
function blockcache_examples_node_insert(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

/**
 * Invalidate the custom tag if entities of type "page" get deleted
 */
function blockcache_examples_node_delete(Node $entity) {
  if($entity->getType() === 'page') {
    Cache::invalidateTags(['blockcache_examples_page_updates']);
  }
}

In your src/Plugin/Block/MyBlock.php (or controller, whatever):

/**
 * Only when node(s) of type 'page' are updated/insert/deleted. See .module file
 */
public function getCacheTags() {
  return Cache::mergeTags(parent::getCacheTags(), array('blockcache_examples_page_updates'));
}

Source: this video explaining block caching

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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