Drupal - Programmatically get all names of an entity reference field

The easiest way to get what you want is something like this:

$names = [];
foreach ($node->field_tags as $item) {
  if ($item->entity) {
    $names[$item->entity->id()] = $item->entity->label();
  }
}

->entity is a so called computed property, it doesn't show up in getValues(). All reference fields have it.

And yes, forget about print_r() on entity or other complex objects. They contain objects that reference each other, and print_r() can't handle that. If you have an entity, always use print_r($entity->toArray()), then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see.


An entity reference field, by definition, can only target one entity type so you can know what your target type is by calling up getSetting() on the field definition.

// Print the targeted entity type field.
$field = \Drupal\field\Entity\FieldStorageConfig::loadByName('node','field_tags');
echo $field->getSetting('target_type');

Or better yet, use EntityReferenceFieldItemList::referencedEntities() to pull up the node's referenced entities and the associated data you need.

// Return an array of Entity objects referenced in the field.
$node->field_tags->referencedEntities();

Tags:

Entities

8