AuthorFormatter.php

Same filename in other branches
  1. 9 core/modules/user/src/Plugin/Field/FieldFormatter/AuthorFormatter.php
  2. 8.9.x core/modules/user/src/Plugin/Field/FieldFormatter/AuthorFormatter.php
  3. 11.x core/modules/user/src/Plugin/Field/FieldFormatter/AuthorFormatter.php

Namespace

Drupal\user\Plugin\Field\FieldFormatter

File

core/modules/user/src/Plugin/Field/FieldFormatter/AuthorFormatter.php

View source
<?php

namespace Drupal\user\Plugin\Field\FieldFormatter;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Plugin implementation of the 'author' formatter.
 */
class AuthorFormatter extends EntityReferenceFormatterBase {
    
    /**
     * {@inheritdoc}
     */
    public function viewElements(FieldItemListInterface $items, $langcode) {
        $elements = [];
        foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
            $elements[$delta] = [
                '#theme' => 'username',
                '#account' => $entity,
                '#link_options' => [
                    'attributes' => [
                        'rel' => 'author',
                    ],
                ],
                '#cache' => [
                    'tags' => $entity->getCacheTags(),
                ],
            ];
        }
        return $elements;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function isApplicable(FieldDefinitionInterface $field_definition) {
        return $field_definition->getFieldStorageDefinition()
            ->getSetting('target_type') == 'user';
    }
    
    /**
     * {@inheritdoc}
     */
    protected function checkAccess(EntityInterface $entity) {
        return $entity->access('view label', NULL, TRUE);
    }

}

Classes

Title Deprecated Summary
AuthorFormatter Plugin implementation of the 'author' formatter.

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