2

I've created a custom block to display info from current user. When i'm logged with username "David", i see on my custom block the username from my last login with other user account.

I have to clear the cache to see the correct username from current user logged.

See here my code :

    class UserProfilBlock extends BlockBase {

  public function build() {

    $userinfo = [];

    $account = \Drupal::currentUser();
    $uid = \Drupal::currentUser()->id();

    $user = \Drupal\user\Entity\User::load($uid);

    $userinfo['name'] = $user->get('name')->value;


    return [
      '#username' => ucfirst($userinfo['name']),
      '#theme' => 'user_info_block',
    ];


  }

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['userprofilinfo_settings'] = $form_state->getValue('userprofilinfo_settings');
  }
}

Something is wrong on my custom module ?

5

I guess the problem is the block is cached for every user. You have to tell Drupal that it should be cached depending on the current logged in user. To do this you have to make use of Cache Tags.

In your case, you have to tell Drupal that the cache of that block should be invalidated when the current logged in user changes. That's because a Cache Context (the user) has changed.

How to do it? You are returning a Render Array, a structure that tells Drupal how to render certain data. In the render array you can set the cache contexts that affect this render array (if the context changes then the cached data changes). In the specific page that talks about the Cacheability of Render Arrays you can see an example of a render array that is cached for each user:

$build = [
  '#markup' => t('Hi, %name, welcome back to @site!', [
    '%name' => $current_user->getUsername(), 
    '@site' => $config->get('name'), 
  ]),
  '#cache' => [
    'contexts' => [ 
      // The "current user" is used above, which depends on the request, 
      // so we tell Drupal to vary by the 'user' cache context.
      'user', 
    ],
  ], 
];

So, I guess that you should add the #cache key to your render array, probably in your theme function, but it may work in the build function (long time since I don't do theming, so I'm not sure).

The code to add is:

'#cache' => [
  'contexts' => ['user']
] 
4

You need to configure the render array's cache to vary when presented with a different user. The core user context can be used for that:

return [
  '#username' => ucfirst($userinfo['name']),
  '#theme' => 'user_info_block',
  '#cache' => [
    'contexts' => ['user'],
  ],
];

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.