AuthorNameFormatter.php

Same filename and directory in other branches
  1. 9 core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php
  2. 8.9.x core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php
  3. 10 core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php

Namespace

Drupal\comment\Plugin\Field\FieldFormatter

File

core/modules/comment/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php

View source
<?php

namespace Drupal\comment\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Plugin implementation of the 'comment_username' formatter.
 */
class AuthorNameFormatter extends FormatterBase {
    
    /**
     * {@inheritdoc}
     */
    public function viewElements(FieldItemListInterface $items, $langcode) {
        $elements = [];
        foreach ($items as $delta => $item) {
            
            /** @var \Drupal\comment\CommentInterface $comment */
            $comment = $item->getEntity();
            $account = $comment->getOwner();
            $elements[$delta] = [
                '#theme' => 'username',
                '#account' => $account,
                '#cache' => [
                    'tags' => $account->getCacheTags() + $comment->getCacheTags(),
                ],
            ];
        }
        return $elements;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function isApplicable(FieldDefinitionInterface $field_definition) {
        return $field_definition->getName() === 'name' && $field_definition->getTargetEntityTypeId() === 'comment';
    }

}

Classes

Title Deprecated Summary
AuthorNameFormatter Plugin implementation of the 'comment_username' formatter.

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