14

I'm trying to get a taxonomy term name by term ID. According to another post, I should load the term first:

$term = \Drupal::entityTypeManager()->getStorage('taxonomy')->load($tid);

But then I get this error :

Notice: Undefined property: Drupal\Core\Entity\Plugin\DataType\EntityReference::$target

What am I doing wrong? How can I get the term name?

3 Answers 3

7
 $term_name = \Drupal\taxonomy\Entity\Term::load($term_id)->get('name')->value;

You will get the Term Name

1
  • Slight change but you can use label() instead of get('name')->value. With all entities, usually, by the way, so you don't need to know whether it's name or anything else.
    – Gábor
    Nov 8, 2020 at 21:03
37

Or you can simply use The entity Term class:

use Drupal\taxonomy\Entity\Term;

and in your code:

$term = Term::load($tid);
$name = $term->getName();
3
  • 3
    My first instinct upon looking at this was "oh no, what about the dependency injection they keep hitting us over the head with in Drupal-land thesedays?", but - on inspection - the static ::load($id) method shared by all types of entities has all of the necessary dependency injection support built in - so this would now be my pick of how to load an entity of any kind (node, comment etc). In fact it beats me why anyone would use the long-hand \Drupal::entityTypeManager()->blah->blah->blah method now! (maybe someone else will chime in and give a good reason for that?) Oct 4, 2018 at 0:23
  • 1
    @DanielScott – \Drupal::entityTypeManager()->getStorage('ENTITY_TYPE_ID')->load($id); is very easy to remember. You simply replace ENTITY_TYPE_ID and then you can load or loadMultiple or loadByProperties etc. And it works for nodes, for terms, for users, for roles, for vocabularies, for node types etc. You can even query the database from it.
    – leymannx
    Jun 10, 2020 at 10:43
  • 1
    @DanielScott, not the question or both answers are about dependency injection. This would look like $this->entityTypeManager->getStorage('ENTITY_TYPE_ID')->load($id);. But the long-hand static call makes refactoring easier if you need DI.
    – 4uk4
    Jun 10, 2020 at 13:39
19

The correct code is the following one.

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

The entity type is taxonomy_term, not taxonomy.

Then, use $term->getName().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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