$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)?
With dpm($account)
I can't see any of my custom fields.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this community\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.
$GLOBALS['user']
doesn't contain a full loaded user object, in Drupal 7; it contains only the information found in the users table.
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 Drupal\user\UserInterface
.
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());
With $account
, you can then access all the fields associated with a user account.
$account = \Drupal::currentUser(): dpm($account);
doesn't show any custom fields? but this answer says how to access user entity fields. Since the question doesn't say which fields the OP is trying to access, the answer just says which method to use. There aren't answers from @batigolix.
\Drupal::currentUser()->id()
and then do a database query, but in D7 they were there on the object already?