1

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?

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

1 Answer 1

2

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

2
  • Adding this cache context should address exactly this problem, see the linked docs.
    – 4uk4
    Apr 29, 2020 at 9:55
  • We used a programmatically generated custom block to solve a similar problem. See the last answer to stackoverflow.com/questions/66549174/… for details. Dec 21, 2022 at 4:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.