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?
2 Answers
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]
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'));
}