I have an entity (a node) with a term reference field. I'd like to access the referenced term entities programmatically, i.e. the fully loaded term objects.

Note that my question could equally apply to any referenced entity, e.g. node entities, user entities, etc.

Here's what I've got so far:

$node = \Drupal\node\Entity\Node::load($nid);

$term_ids = array();
$items = $node->field_tags->getValue();
foreach ($items as $item) {
  $term_ids[] = $item['target_id'];

$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($term_ids);

It works, but I'm not very happy with it:

  • It lacks abstraction (how am I supposed to know that the id of the referenced entity is in $item['target_id']?)
  • It's not very generic (it works if the field references terms, but what if it references nodes or users?

Any better solution?


The following $node->get('tags')-referencedEntities() will return a list of all the referenced entities.

  • Awesome, Eyal. That's exactly what I was looking for, thanks! Apr 28 '16 at 16:47

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.