In the build() function of my custom block I'm using the code below to get a field value for the currently logged in user. However, the value returned is for the wrong user (someone who has previously logged in). When I clear the cache the value computes correctly. As you can imagine, this is a big problem for my application!

    $user = \Drupal::currentUser();
    // hide if not logged in
    if ($user->id() < 1) {
      return;
    }
    // get the customer id for this user
    $userNode = \Drupal\user\Entity\User::load($user->id());
    $customerid = $userNode->get('field_account_number')->value;

Comments

mrphilipwarner created an issue. See original summary.

mrphilipwarner’s picture

Title: \Drupal::currentUser() returnng cached value » \Drupal::currentUser() returning cached value
maacl’s picture

Category: Bug report » Support request
mrphilipwarner’s picture

Thank you!

I added the following cache item to the return array and it's working now!

return array(
      '#markup' => $this->t($markup),
      '#cache' => array(
        'contexts' => array('user'),
      ),
      '#attached' => array(
        'library' => array(
          'smsw_reporting/reporting',
        ),
        'drupalSettings' => array(
          'customerid' => $customerid
        )
      )
    );
maacl’s picture

Status: Active » Closed (works as designed)

This should be enough in this case. If you happen to render other content (like nodes) inside your block you have to embed the getCacheContexts() function and merge the contexts to have a proper bubbling of contexts.