The answer to "Is there a function to get the current user object that avoids accessing the global variable?" includes this:

In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS['user']

I tried to use the following code:

$user = \Drupal::currentUser(); 
$name = $user->get('name')->value;

But that results in an error like so:

Fatal error: Call to undefined method Drupal\Core\Session\AccountProxy::get() in /home/remindme/uhoc.org/modules/testmodule/src/Form/FruitForm.php on line 173 (Line 173 is $name = $user->get('name')->value;

Do I need to used some namespace or there is some other way to access the user object?


Yes you need to use a name space, you can include the name space directly like this

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$name = $user->get('name')->value;
  • 1
    The namespace isn't the issue. It's the difference between the Account and the User. IMHO, the docs on \Drupal::currentUser are misleading, especially when you are using an editor that doesn't autocomplete. – mpdonadio Apr 26 '16 at 1:33
  • 2
    You may also use $account = \Drupal::currentUser()->getAccount(); to load the full user account – David Thomas Jan 29 '19 at 4:45
  • @DavidThomas altho, doing that does not give you access to the user fields other than e-mail. So it doesn't really load the full user account. – No Sssweat Jan 29 '19 at 6:14
  • @NoSssweat thanks, but I just checked and could get the user fields ok from $account after ->getAccount(). e.g var_export($account->get('field_example')->value); or var_export($account->toArray()); was ok with field data included. You can see it calls loadUserEntity in the api docs – David Thomas Jan 29 '19 at 8:07
  • Well, doing $account->toArray() or $account->get() throws an error Call to undefined method Drupal\Core\Session\UserSession::get() same for toArray(). I wonder if you're using a contrib module that makes this possible. I'm testing this on a fresh install of tho a bit outdated, 8.6.3 – No Sssweat Jan 29 '19 at 8:15

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