function UserNameFormatter::viewElements

Same name in other branches
  1. 9 core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php \Drupal\user\Plugin\Field\FieldFormatter\UserNameFormatter::viewElements()
  2. 8.9.x core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php \Drupal\user\Plugin\Field\FieldFormatter\UserNameFormatter::viewElements()
  3. 11.x core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php \Drupal\user\Plugin\Field\FieldFormatter\UserNameFormatter::viewElements()

Overrides FormatterInterface::viewElements

File

core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php, line 53

Class

UserNameFormatter
Plugin implementation of the 'user_name' formatter.

Namespace

Drupal\user\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
        
        /** @var \Drupal\user\UserInterface $user */
        if ($user = $item->getEntity()) {
            if ($this->getSetting('link_to_entity')) {
                $elements[$delta] = [
                    '#theme' => 'username',
                    '#account' => $user,
                    '#link_options' => [
                        'attributes' => [
                            'rel' => 'user',
                        ],
                    ],
                    '#cache' => [
                        'tags' => $user->getCacheTags(),
                    ],
                ];
            }
            else {
                $elements[$delta] = [
                    '#markup' => $user->getDisplayName(),
                    '#cache' => [
                        'tags' => $user->getCacheTags(),
                    ],
                ];
            }
        }
    }
    return $elements;
}

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