diff --git a/src/Plugin/Field/FieldFormatter/EntityReferenceRevisionsFormatterBase.php b/src/Plugin/Field/FieldFormatter/EntityReferenceRevisionsFormatterBase.php index e098f52..1535682 100644 --- a/src/Plugin/Field/FieldFormatter/EntityReferenceRevisionsFormatterBase.php +++ b/src/Plugin/Field/FieldFormatter/EntityReferenceRevisionsFormatterBase.php @@ -13,14 +13,18 @@ abstract class EntityReferenceRevisionsFormatterBase extends EntityReferenceForm * {@inheritdoc} */ public function prepareView(array $entities_items) { - // Entity revision loading currently has no static/persistent cache and no - // multiload. As entity reference checks _loaded, while we don't want to - // indicate a loaded entity, when there is none, as it could cause errors, - // we actually load the entity and set the flag. foreach ($entities_items as $items) { foreach ($items as $item) { - - if ($item->entity) { + // To avoid trying to reload non-existent entities in + // getEntitiesToView(), explicitly mark the items where $item->entity + // contains a valid entity ready for display. All items are initialized + // at FALSE. + $item->_loaded = FALSE; + if ($item->getReferencedEntity() !== NULL) { + $item->entity = $item->getReferencedEntity(); + $item->_loaded = TRUE; + } + elseif ($item->hasNewEntity()) { $item->_loaded = TRUE; } } diff --git a/src/Plugin/Field/FieldType/EntityReferenceRevisionsItem.php b/src/Plugin/Field/FieldType/EntityReferenceRevisionsItem.php index 8b25f4d..fc1e82a 100644 --- a/src/Plugin/Field/FieldType/EntityReferenceRevisionsItem.php +++ b/src/Plugin/Field/FieldType/EntityReferenceRevisionsItem.php @@ -202,6 +202,25 @@ class EntityReferenceRevisionsItem extends EntityReferenceItem implements Option } /** + * Returns the referenced entity at the correct revision. + */ + public function getReferencedEntity() { + if (isset($this->entity)) { + return $this->entity; + } + elseif (isset($this->target_id)) { + $storage = \Drupal::entityTypeManager()->getStorage($this->getSetting('target_type')); + // By default always load the default revision, so caches get used. + $entity = $storage->load($this->target_id); + if ($entity !== NULL && $entity->getRevisionId() != $this->revision_id) { + // A non-default revision is a referenced, so load this one. + $entity = $storage->loadRevision($this->revision_id); + } + return $entity; + } + } + + /** * {@inheritdoc} */ public function onChange($property_name, $notify = TRUE) {