You are here

public function EntityReferenceRevisionsFieldItemList::referencedEntities in Entity Reference Revisions 8

Gets the entities referenced by this field, preserving field item deltas.

Return value

\Drupal\Core\Entity\EntityInterface[] An array of entity objects keyed by field item deltas.

Overrides EntityReferenceFieldItemList::referencedEntities

File

src/EntityReferenceRevisionsFieldItemList.php, line 21

Class

EntityReferenceRevisionsFieldItemList
Defines a item list class for entity reference fields.

Namespace

Drupal\entity_reference_revisions

Code

public function referencedEntities() {
  if (empty($this->list)) {
    return array();
  }

  // Collect the IDs of existing entities to load, and directly grab the
  // "autocreate" entities that are already populated in $item->entity.
  $target_entities = $ids = array();
  foreach ($this->list as $delta => $item) {
    if ($item
      ->hasNewEntity()) {
      $target_entities[$delta] = $item->entity;
    }
    elseif ($item->target_revision_id !== NULL) {
      $ids[$delta] = $item->target_revision_id;
    }
  }

  // Load and add the existing entities.
  if ($ids) {
    $target_type = $this
      ->getFieldDefinition()
      ->getSetting('target_type');
    foreach ($ids as $delta => $target_id) {
      $entity = \Drupal::entityTypeManager()
        ->getStorage($target_type)
        ->loadRevision($target_id);
      if ($entity) {
        $target_entities[$delta] = $entity;
      }
    }

    // Ensure the returned array is ordered by deltas.
    ksort($target_entities);
  }
  return $target_entities;
}