You are here

public function FileUrlFormatter::prepareView in File URL 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldFormatter/FileUrlFormatter.php \Drupal\file_url\Plugin\Field\FieldFormatter\FileUrlFormatter::prepareView()

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

Overrides EntityReferenceFormatterBase::prepareView

File

src/Plugin/Field/FieldFormatter/FileUrlFormatter.php, line 119

Class

FileUrlFormatter
Plugin implementation of the 'file_default' formatter.

Namespace

Drupal\file_url\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().
  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)) {
        $file = FileUrlHandler::urlToFile($item->target_id);
        $entities[$item->target_id] = $file;
      }
    }
  }

  // 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($entities[$item->target_id])) {
        $item->entity = $entities[$item->target_id];
        $item->_loaded = TRUE;
      }
      elseif ($item
        ->hasNewEntity()) {
        $item->_loaded = TRUE;
      }
    }
  }
}