Drupal 8: Looping through EntityReferenceItem(s) / EntityReferenceRevisionsItem(s) to get Target Entities is wrong

I just had the case to iterate over EntityReferenceRevisionsItem's which are similar to EntityReferenceItem to get the target entities,

My code snippet was (WRONG EXAMPLE):

  1. $subParagraphsER = $paragraph->get('field_paragraphs_paragraphs');
  2. foreach ($subParagraphsER as $subParagraph) {
  3. ...
  4. }

I expected to either get the target entities directly in the foreach or have a getTarget() function or something like that. But that's not the case.

To iterate over Entity reference (revision) targets the right approach is (RIGHT EXAMPLE):

  1. $subParagraphs = $paragraph->get('field_paragraphs_paragraphs')->referencedEntities();
  2. foreach ($subParagraphs as $subParagraph) {
  3.   ...
  4. }

Comments

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.

More information about formatting options