18

I have a custom form that needs to display a default value from a custom user field. The field was created under /admin/config/people/accounts/fields and its machine name is field_r_period_length_sec.

//get user
$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$r_period = $userCurrent->field_r_period_length_sec;

However, the value doesn't show and I get this error:

Notice: Undefined property: Drupal\Core\Session\AccountProxy::$field_r_period_length_sec

What am I doing wrong?

4 Answers 4

28

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();
1
  • 2
    For anyone wanting remove the warning from PHPStorm in $r_period = $user->field_r_period_length_sec->value; add this comment /** @var $user \Drupal\user\Entity\User */ above $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    – Neil Nand
    Commented Jan 17, 2019 at 11:48
4

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.

3

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
2
  • Thanks! I was able to get specific field from the user profile. But im wondering how can you set/update a profile field name? TIA Commented Aug 23, 2018 at 8:25
  • 1
    $profile->set('field_name', value)
    – Denis K
    Commented Aug 25, 2018 at 4:11
1

Entity::load() is based off of \Drupal::entityManager(); which is deprecated.

A better way to do this is by using entityTypeManager().

$user = \Drupal::entityTypeManager()->getStorage('user')->load($current_user->id());
$r_period = $user->field_r_period_length_sec->value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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