12

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?

15

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();
  • 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 Jan 17 '19 at 11:48
3

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.

2

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
  • 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 – John Rey Tanquinco Aug 23 '18 at 8:25
  • 1
    $profile->set('field_name', value) – Denis Kolmerschlag Aug 25 '18 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, privacy policy and cookie policy

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