Problem setting user specific cache tags on custom block with user context

Created on 2 December 2019, almost 5 years ago
Updated 4 December 2023, 9 months ago

I have a simple custom block with a user cache context and a specific user specific cache tag:

/**
 * Provides a 'User example' block.
 *
 * @Block(
 *   id = "user_example_block",
 *   admin_label = @Translation("User example block"),
 *   category = @Translation("Blocks")
 * )
 */
class UserExampleBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => '<span>Current User ID: ' . \Drupal::currentUser()->id() . '</span>',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts()  {
    return Cache::mergeContexts(parent::getCacheContexts(), ['user']);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return Cache::mergeTags(parent::getCacheTags(), array('example_user:' . \Drupal::currentUser()->id()));
  }
}

The block output varies correctly by the logged in user but the user specific cache tag is not set correctly.
It seems the cache tag is only set once for users with the same role or permissions.

Here is how to reproduce it:

1. Rebuild cache (drush cr)
2. Login with User 100 -> The block output is correct. The correct cache tag is set (example_user:100).
3. Logout
4. Login with User 101 (same role as User 100) -> The output of the block is correct, but the cache tag was not changed, it still is example_user:100. In fact the getCacheTags, getCacheContexts methods were not even called.

What works is when I put the cacheability meta data in the build method (with the "#cache" element in the render array).

What could be the reason for this?

Thanks for any help.

πŸ› Bug report
Status

Closed: outdated

Version

9.4

Component
BlockΒ  β†’

Last updated 3 days ago

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡¨πŸ‡¦Canada joseph.olstad

    @Lendude, I have a custom controller and when I specify contexts => ['user'] the behavior seems to me as if every time I load the page for the same user, it's not actually loading from the cache.

          '#cache' => [
            'tags' => $node->getCacheTags(),
            'contexts' => ['user'],
          ],
    

    So this appears to be doing the same thing as #cache => ['max_age' => 0]

    I was expecting something cached when I reloaded the page, however I made a small change to a label in the controller code and it shows up instantly.

Production build 0.71.5 2024