You are here

public function EntityReferenceFormatterBase::prepareView in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::prepareView()
  2. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::prepareView()

Loads the entities referenced in that field across all the entities being viewed.

Overrides FormatterBase::prepareView

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php, line 119

Class

EntityReferenceFormatterBase
Parent plugin for entity reference formatters.

Namespace

Drupal\Core\Field\Plugin\Field\FieldFormatter

Code

public function prepareView(array $entities_items) {

  // Collect entity IDs to load. For performance, we want to use a single
  // "multiple entity load" to load all the entities for the multiple
  // "entity reference item lists" being displayed. We thus cannot use
  // \Drupal\Core\Field\EntityReferenceFieldItemList::referencedEntities().
  $ids = [];
  foreach ($entities_items as $items) {
    foreach ($items as $item) {

      // 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 ($this
        ->needsEntityLoad($item)) {
        $ids[] = $item->target_id;
      }
    }
  }
  if ($ids) {
    $target_type = $this
      ->getFieldSetting('target_type');
    $target_entities = \Drupal::entityTypeManager()
      ->getStorage($target_type)
      ->loadMultiple($ids);
  }

  // For each item, pre-populate the loaded entity in $item->entity, and set
  // the 'loaded' flag.
  foreach ($entities_items as $items) {
    foreach ($items as $item) {
      if (isset($target_entities[$item->target_id])) {
        $item->entity = $target_entities[$item->target_id];
        $item->_loaded = TRUE;
      }
      elseif ($item
        ->hasNewEntity()) {
        $item->_loaded = TRUE;
      }
    }
  }
}