6

I have a taxonomy term reference field attached to my user account.

I tried getting the value programatically in the same way as I get the value for text fields, but it doesn't work.

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;
// Does not return the correct value.
$termreference = $account->get('field_termreference')->value;

How am I supposed to get the value (name) of the referenced term programatically?

3 Answers 3

14

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.

5
  • 9
    The entity should already be available turning it into a one-liner: $name = $account->get('field_termreference')->entity->getName();
    – Clive
    Sep 19, 2017 at 20:02
  • Note that this will only work with a single-value taxonomy term field.
    – diamondsea
    May 15, 2018 at 10:12
  • 8
    For a multi-value field: $terms = $account->get('field_termreference')->referencedEntities();
    – 4uk4
    Feb 20, 2019 at 16:30
  • Hai this actually works for me .. $name gave me the last child of that taxonomy.. how to get parent name of above 3 parents.. like i have a hierarchy in taxonomy.
    – Rifas Ali
    Jun 26, 2019 at 6:10
  • @RifasAli this is another question, you need to create a new question. Jun 26, 2019 at 14:44
3

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();
0

field_taxonomy->value; not work. Only ->target_id; But if you use the module Field Token Value, you could access to the name of field_taxonomy saved as plain text like field_taxonomy_from_token_value->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.