I've created a custom entity and having trouble providing proper caching.

When you create custom entity, by default it has only one cache tag entity_type:id.

Problem is, I need to display same entity to different users (by role) in a different way.

So I think I need cache tags, such as entity_type:id:user_role? How do I go with this?

  • 1
    You want to set cache context by role: drupal.org/docs/8/api/cache-api/cache-contexts – Jaypan Aug 13 '19 at 5:56
  • Yes, this is a context. The permission based context is set by default, so you rarely need to set an extra role context, unless you have users with different roles resulting in the same permissions. – 4k4 Aug 13 '19 at 6:25
  • Can you explain that a little more 4k4? Are you saying that the cache context is automatically set by permissions by default, and therefore does not require explicit cache contexts to be set? – Jaypan Aug 14 '19 at 0:30

To add a cache dependency on user roles you don't need a cache tag, but a cache context user.roles.

However, you rarely need this context, because there is already a default render context for the hashed user permissions user.permissions, set in the container variable required_cache_contexts, which is applied on all render arrays:


    # Renderer required cache contexts:
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

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.