Drupal - How to programatically access the value of a taxonomy term reference?
As the taxonomy term is a reference the value (or label) is not stored in the user entity, just the target_id. So you need to use:
$termreference = $account->get('field_termreference')->target_id;
This should be your code:
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;
$account = User::load($account->id());
// Returns the correct value.
$textfield = $account->get('field_textfield')->value;
// You need to use the target_id to access to the value.
$termreference = $account->get('field_termreference')->target_id;
Now you need to search the label:
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termreference);
$name = $term->getName();
Your taxonomy label (name) will be in $name
.
There is a slightly cleaner way to do this. When calling ->get('field_name')
on a reference field it returns an instance of EntityReferenceFieldItemList
. You can use this as an array and access the target_id
and manually load the \Drupal::entityTypeManger()
to subload, but that class actually has a method that does this for you:
$entity->get('field_tags')->referencedEntities();