'Getting Taxonomy term name from target ID - D9

Getting Taxonomy term name from Taxonomy target ID:

I have a taxonomy term that accepts multiple values. It's rendered as a multiselectfield. I am trying to read the target ID of the field and figure the term name out of it using the below code in a preprocess function:

 $granttype = $user_entity->field_user_grant_type->getValue();
  foreach($granttype as $gt)
  {
    $granttype_name = \Drupal\taxonomy\Entity\Term::load($gt)->label();
  }
  dd($granttype_name);
  
  $variables['grant_type'] = $granttype_name;
  

dd($granttype) shows the below output:

enter image description here

However, the foreach loop to figure out the term name is not working correctly.

dd($granttype_name) results as:

 The website encountered an unexpected error. Please try again later.
TypeError: Illegal offset type in Drupal\Core\Entity\EntityStorageBase->load() (line 297 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).

I am looping through the target ID and trying to get the term name. But it's not working. Any help pls?


UPDATE: I tried the below line of code:

 $term = term::load($gt);
    $name = $term->getName();

still no luck :( same error



Solution 1:[1]

Here is an example how to do this:

  $grant_type = $user_entity->field_user_grant_type->entity;
  if ($grant_type instanceof \Drupal\taxonomy\TermInterface) {
    var_dump($grant_type->label());
  }

If you have multiple referenced terms, use:

  $grant_types = $user_entity->field_user_grant_types->referencedEntities();
  foreach ($grant_types as $grant_type) {
    var_dump($grant_type->label());
  }

Explanation:

  1. The generic way to get entity title is the Entity::label method $term->label();
  2. There is a helpful method Entity::referencedEntities to get relations.

Solution 2:[2]

First, you need to include

use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;

Second, retrieve the value(s) stored in your field (field_user_grant_type) and store them in an array:

$myArray = array();
$granttype = $user_entity->get('field_user_grant_type')->getValue();

$granttype will now contain an array of arrays. Next, you need to gather the actual term IDs

foreach($granttype as $type){
   $myArray[] = $type['target_id'];
}

Finally, loop through $myArray and fetch the term IDs stored there, and then use each ID to get its corresponding Term Name. Here, I store them in a new array called grantTypeNames

grantTypeNames = array();
foreach($myArray as $term_id){
   $grantTypeNames[] = Term::load($term_id)->get('name')->value;
}

The array $grantTypeNames will now contain the term names you want. I hope that helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 milkovsky
Solution 2 RainMaker