$account = \Drupal::currentUser() loads the user object into
$account, but how do I access custom fields I've created on the user object (via the admin UI)?
dpm($account) I can't see any of my custom fields.
\Drupal::currentUser() returns an
Drupal\Core\Session\AccountInterface object. That could be a full user (that would be a
Drupal\user\UserInterface), but right now, for the default authentication method, it is not.
Use this to get the user entity and all the fields:
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
D7 had exactly the same behavior, the difference now is just that in D7, they were simply different stdClass'es, now you have explicit interfaces to differentiate the two.
And here is how to get it out of that object:
// Load the current user. $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); // Get field data from that user. $website = $user->get('field_website')->value; $body = $user->get('body')->value; // Some default getters include. $email = $user->get('mail')->value; $name = $user->get('name')->value; $uid= $user->get('uid')->value;
Drupal::currentUser() returns an object implementing
Drupal\Core\Session\AccountProxyInterface. That is different from what returned from
User::load(), which is an object implementing
This means it's not assured you get a full
User object with its fields loaded, but it's not even assured you get a
User object. As consequence, you call call some of the methods available from the
User class, such as
User::get(). You can call
AccountInterface::id(), which returns the user ID; with that, you can then load the full
User object with
User::load() and have access to all the fields modules attached to the entity.
use Drupal\Core\Session\AccountProxyInterface; use Drupal\user\Entity\User; $account = User::load(\Drupal::currentUser()->id());
$account, you can then access all the fields associated with a user account.