2

Is there any easy way to clear the cache for a custom entity? I know there is an entry in the cache_entity-Table. If i manually delete it, everything is fine. I tried doing the same as in \Drupal\Core\Entity->invalidateTagsOnSave() or \Drupal\Core\Entity->invalidateTagsOnDelete(). This does not seem to change anything.

Unfortunately I can't just load the entity and resave it in this situation.

  • Are you adding any cache tags or contexts or data to the entity itself? – Kevin Feb 9 '18 at 20:21
8

But you know the entity ID that you want to have invalidated?

Then use \Drupal::entityTypeManager()->getStorage($entity_type_id)->resetCache([$id]);

1

In your custom entity you should override the function

public function getCacheTagsToInvalidate();

of the EntityInterface.

Then, to clear that entity's cache you simply call

\Drupal\Core\Cache\Cache::invalidateTags($entity->getCacheTagsToInvalidate());

If you do not override getCacheTagsToInvalidate() the default implementation in entity.php should also work:

public function getCacheTagsToInvalidate() {
    if ($this->isNew()) {
      return [];
    }
    return [$this->entityTypeId . ':' . $this->id()];
  }

The tags[] is just the name plus the id.

  • Will this also invalidate the {entity_type_id}_list tag? – Luke A. Leber Nov 26 '18 at 23:37
  • It's your custom entity. If your cache on the {entity_type_id}_list tag depends on a single instance, then add this tag to your getCacheTagsToInvalidate() return array. – Rainer Feike Nov 27 '18 at 7:26

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.