11

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?

33

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();
| improve this answer | |
  • 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?) – Daniel Scott Oct 4 '18 at 0:23
  • @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 at 10:43
  • @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. – 4k4 Jun 10 at 13:39
14

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().

| improve this answer | |

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.