Drupal - Get the value of a custom user field

Berdir's answer gave me a search term that got me this:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

After a bit of trial and error, this is the code that works, in case anyone else needs:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$r_period = $user->field_r_period_length_sec->value;

For multiple values, use

$r_period = $user->get('field_r_period_length_sec')->getValue();

The current user object is not a user entity. You need to load the user with that ID to access any field except the information specified by AccountInterface.


I don't know since when these answers doesn't work anymore, but with Drupal 8.5 the above solution return null all the time.

After investigation the solution to access custom field from a user profile is:

$activeProfile = \Drupal::getContainer()
  ->get('entity_type.manager')
  ->getStorage('profile')
  ->loadByUser(User::load([uid]), '[profile_machine_name]');

Then you can do

$activeProfile->field_xxx->value

Tags:

Users

8