1

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?

2 Answers 2

6

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

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

You can use the get() method of the field object to retrieve the referenced entities as fully loaded objects instead of just their IDs. Here's an example:

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

$terms = $node->field_tags->referencedEntities();

This will return an array of fully loaded term objects.

If you need to access the referenced entities of a field that can reference different types of entities (e.g. nodes, terms, users), you can use the getTargetEntityTypeId() method of the field object to determine the type of entity being referenced, and then use the appropriate entity type manager to load the referenced entities. Here's an example:

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

$field_name = 'field_example'; // Replace with your field name.
$field = $node->$field_name;

$entity_type_id = $field->getSetting('target_type');
$entity_type_manager = \Drupal::entityTypeManager();
$referenced_entities = $entity_type_manager->getStorage($entity_type_id)->loadMultiple($field->getValue());

This will load all the referenced entities of the field, regardless of their entity type.

Using this approach provides more abstraction and flexibility, making your code more generic and easier to maintain.

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.