You are here

public function UserNameFormatter::viewElements in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php \Drupal\user\Plugin\Field\FieldFormatter\UserNameFormatter::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

core/modules/user/src/Plugin/Field/FieldFormatter/UserNameFormatter.php, line 57
Contains \Drupal\user\Plugin\Field\FieldFormatter\UserNameFormatter.

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 $user \Drupal\user\UserInterface */
    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;
}