How to loop through referenced entities?

Let's say that your Basic page content type has two referenced fields. One is Entity reference to Articles and one is Entity reference revisions to a Paragraph type called Vote.

How would you loop through the first field and get all Article titles? Or how would you loop through the second field and get all votes? It's very easy. Both Entity reference and Entity reference revisions fields have referencedEntities() method that doesn't exist in the FieldItemList class, that both of these fields extend.

You can get Article titles like this:

$article_titles = [];
    
$basic_page = Drupal\node\Entity\Node::load($your_node_id);
    
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $articles */
$articles = $basic_page->get('field_articles');
    
/** @var \Drupal\node\Entity\Node $article */
foreach ($articles->referencedEntities() as $article) {
  $article_titles[] = $article->getTitle();
}

In the same way, you can get all Paragraphs:

$total_votes = 0;

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

/** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $votes */
$votes = $basic_page->get('field_votes');

/** @var \Drupal\paragraphs\Entity\Paragraph $vote */
foreach ($votes->referencedEntities() as $vote) {
  $total_votes += $vote->field_vote->value;
}

Method referencedEntities() is doing all the hard work for you, so that you don't have to first get entity target ids and then load each entity. You can see what this method does here: EntityReferenceFieldItemList.php#L26

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.