Reputation: 380
I am trying to access the content of custom fields in the user object.
Some have advocated the user of user_load. But according to Drupal, that deprecated.
in Drupal 8.x, will be removed before Drupal 9.0. Use \Drupal\user\Entity\User::load().
So I've attempted to use Entity::load. It loads the object and in my IDE, I can see the values... but I can't seem to load a local variable with the value. Here is code that isn't working.
public function arguments($arg1) {
$userProfile = \Drupal\user\Entity\User::load($arg1);
$display_username = $userProfile->getAccountName();
$current_user = user_load($user_id);
$lastname = $userProfile->values["field_user_last_name"]["x-default"][0]["value"];
That string came from the path I saw in the object returned. However, as one can see in the screen shot from the IDE, the value comes back NULL.
I'm sure it is something simple that I'm not seeing. (missing the good old days of non-OOP!)
Upvotes: 2
Views: 4456
Reputation: 421
The $userProfile
is an object so data should be called via methods.
The list of all methods can be found in Drupal documentation.
Long story short, all Drupal entities use the same methods to return field value.
The get('field_name')
method returns the field object and getValue()
returns the value of field.
In your case that would be:
$field_value = $userProfile->get('field_user_last_name')->getValue()[0]["value"];
By using so called magic methods the code will look even cleaner and you can simply get the value as:
$field_value = $userProfile->field_user_last_name->value;
Please note that magic methods can not be always used while standard methods can be.
Upvotes: 4