I have built a Drupal 8 site, we are showing the user name and last name on a block, this is my code on preprocess from .theme file:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

$firstname = $user->get('field_firstname')->value;

$firstname = $firstname;
$variables['firstname'] = $firstname;

Then in the block im doing: Hello {{ firstname }}

And it shows the last user, not mine. When I do drush cr then I get the correct name, why? How can I fix this and already display the right username?

  • add to your block class this method public function getCacheMaxAge() { return 0; } – berramou Apr 27 at 23:47
  • not sure what you mean, im using this on the _preprocess(&$variables, $hook) { of the theme.. – lucasvm1980 Apr 28 at 0:09
  • you process your block with THEME_preprocess_block ? – berramou Apr 28 at 0:26

You are retrieving the user name from the current context and the user entity, but then you make it a dumb string value to pass it to the template. Include the cache metadata to define where this value is coming from and under which circumstances it could change:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$firstname = $user->get('field_firstname')->value;

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

More info https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

| improve this answer | |
  • Adding this cache context should address exactly this problem, see the linked docs. – 4k4 Apr 29 at 9:55

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.