class EntityReferenceFormatterBase

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase
  2. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase
  3. 11.x 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

4 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
EntityTestReferenceCustomCacheTagFormatter.php in core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldFormatter/EntityTestReferenceCustomCacheTagFormatter.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

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
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 13
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 14
FormatterBase::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterInterface::settingsForm 25
FormatterBase::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterInterface::settingsSummary 23
FormatterBase::__construct public function Constructs a FormatterBase object. 13
FormatterInterface::viewElements public function Builds a renderable array for a field value. 48
PluginInspectionInterface::getPluginDefinition public function Gets the definition of the plugin implementation. 6
PluginInspectionInterface::getPluginId public function Gets the plugin_id of the plugin instance. 2
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 6
PluginSettingsBase::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsInterface::defaultSettings 43
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 3
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

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.