You are here

public function EntityReferenceFormatterBase::view in Drupal 9

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::view()
  2. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::view()

Overrides FormatterBase::view

See also

::prepareView()

::getEntitiesToView()

File

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

Class

EntityReferenceFormatterBase
Parent plugin for entity reference formatters.

Namespace

Drupal\Core\Field\Plugin\Field\FieldFormatter

Code

public function view(FieldItemListInterface $items, $langcode = NULL) {
  $elements = parent::view($items, $langcode);
  $field_level_access_cacheability = new CacheableMetadata();

  // Try to map the cacheability of the access result that was set at
  // _accessCacheability in getEntitiesToView() to the corresponding render
  // subtree. If no such subtree is found, then merge it with the field-level
  // access cacheability.
  foreach ($items as $delta => $item) {

    // Ignore items for which access cacheability could not be determined in
    // prepareView().
    if (!empty($item->_accessCacheability)) {
      if (isset($elements[$delta])) {
        CacheableMetadata::createFromRenderArray($elements[$delta])
          ->merge($item->_accessCacheability)
          ->applyTo($elements[$delta]);
      }
      else {
        $field_level_access_cacheability = $field_level_access_cacheability
          ->merge($item->_accessCacheability);
      }
    }
  }

  // Apply the cacheability metadata for the inaccessible entities and the
  // entities for which the corresponding render subtree could not be found.
  // This causes the field to be rendered (and cached) according to the cache
  // contexts by which the access results vary, to ensure only users with
  // access to this field can view it. It also tags this field with the cache
  // tags on which the access results depend, to ensure users that cannot view
  // this field at the moment will gain access once any of those cache tags
  // are invalidated.
  $field_level_access_cacheability
    ->merge(CacheableMetadata::createFromRenderArray($elements))
    ->applyTo($elements);
  return $elements;
}