You are here

abstract class EntityReferenceFormatterBase 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
  2. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase

Parent plugin for entity reference formatters.

Hierarchy

Expanded class hierarchy of EntityReferenceFormatterBase

3 files declare their use of EntityReferenceFormatterBase
AuthorFormatter.php in core/modules/user/src/Plugin/Field/FieldFormatter/AuthorFormatter.php
EntityReferenceTaxonomyTermRssFormatter.php in core/modules/taxonomy/src/Plugin/Field/FieldFormatter/EntityReferenceTaxonomyTermRssFormatter.php
FileFormatterBase.php in core/modules/file/src/Plugin/Field/FieldFormatter/FileFormatterBase.php

File

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

Namespace

Drupal\Core\Field\Plugin\Field\FieldFormatter
View source
abstract class EntityReferenceFormatterBase extends FormatterBase {

  /**
   * Returns the referenced entities for display.
   *
   * The method takes care of:
   * - checking entity access,
   * - placing the entities in the language expected for display.
   * It is thus strongly recommended that formatters use it in their
   * implementation of viewElements($items) rather than dealing with $items
   * directly.
   *
   * For each entity, the EntityReferenceItem by which the entity is referenced
   * is available in $entity->_referringItem. This is useful for field types
   * that store additional values next to the reference itself.
   *
   * @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items
   *   The item list.
   * @param string $langcode
   *   The language code of the referenced entities to display.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]
   *   The array of referenced entities to display, keyed by delta.
   *
   * @see ::prepareView()
   */
  protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
    $entities = [];
    foreach ($items as $delta => $item) {

      // Ignore items where no entity could be loaded in prepareView().
      if (!empty($item->_loaded)) {
        $entity = $item->entity;

        // Set the entity in the correct language for display.
        if ($entity instanceof TranslatableInterface) {
          $entity = \Drupal::service('entity.repository')
            ->getTranslationFromContext($entity, $langcode);
        }
        $access = $this
          ->checkAccess($entity);

        // Add the access result's cacheability, ::view() needs it.
        $item->_accessCacheability = CacheableMetadata::createFromObject($access);
        if ($access
          ->isAllowed()) {

          // Add the referring item, in case the formatter needs it.
          $entity->_referringItem = $items[$delta];
          $entities[$delta] = $entity;
        }
      }
    }
    return $entities;
  }

  /**
   * {@inheritdoc}
   *
   * @see ::prepareView()
   * @see ::getEntitiesToView()
   */
  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;
  }

  /**
   * {@inheritdoc}
   *
   * Loads the entities referenced in that field across all the entities being
   * viewed.
   */
  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;
        }
      }
    }
  }

  /**
   * Returns whether the entity referenced by an item needs to be loaded.
   *
   * @param \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item
   *   The item to check.
   *
   * @return bool
   *   TRUE if the entity needs to be loaded.
   */
  protected function needsEntityLoad(EntityReferenceItem $item) {
    return !$item
      ->hasNewEntity();
  }

  /**
   * Checks access to the given entity.
   *
   * By default, entity 'view' access is checked. However, a subclass can choose
   * to exclude certain items from entity access checking by immediately
   * granting access.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to check.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   A cacheable access result.
   */
  protected function checkAccess(EntityInterface $entity) {
    return $entity
      ->access('view', NULL, TRUE);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityReferenceFormatterBase::checkAccess protected function Checks access to the given entity. 3
EntityReferenceFormatterBase::getEntitiesToView protected function Returns the referenced entities for display. 1
EntityReferenceFormatterBase::needsEntityLoad protected function Returns whether the entity referenced by an item needs to be loaded. 1
EntityReferenceFormatterBase::prepareView public function Loads the entities referenced in that field across all the entities being viewed. Overrides FormatterBase::prepareView
EntityReferenceFormatterBase::view public function Overrides FormatterBase::view
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 12
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterInterface::isApplicable 12
FormatterBase::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterInterface::settingsForm 19
FormatterBase::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterInterface::settingsSummary 17
FormatterBase::__construct public function Constructs a FormatterBase object. Overrides PluginBase::__construct 12
FormatterInterface::viewElements public function Builds a renderable array for a field value. 35
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition.
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function
PluginBase::getDerivativeId public function
PluginBase::getPluginDefinition public function 1
PluginBase::getPluginId public function
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 4
PluginSettingsBase::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsInterface::defaultSettings 34
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 1
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 1
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.