1<?php
2
3namespace Drupal\user\Plugin\Field\FieldFormatter;
4
5use Drupal\Core\Field\FieldDefinitionInterface;
6use Drupal\Core\Field\FieldItemListInterface;
7use Drupal\Core\Field\FormatterBase;
8use Drupal\Core\Form\FormStateInterface;
9
10/**
11 * Plugin implementation of the 'user_name' formatter.
12 *
13 * @FieldFormatter(
14 *   id = "user_name",
15 *   label = @Translation("User name"),
16 *   description = @Translation("Display the user or author name."),
17 *   field_types = {
18 *     "string"
19 *   }
20 * )
21 */
22class UserNameFormatter extends FormatterBase {
23
24  /**
25   * {@inheritdoc}
26   */
27  public static function defaultSettings() {
28    $options = parent::defaultSettings();
29
30    $options['link_to_entity'] = TRUE;
31    return $options;
32  }
33
34  /**
35   * {@inheritdoc}
36   */
37  public function settingsForm(array $form, FormStateInterface $form_state) {
38    $form = parent::settingsForm($form, $form_state);
39
40    $form['link_to_entity'] = [
41      '#type' => 'checkbox',
42      '#title' => $this->t('Link to the user'),
43      '#default_value' => $this->getSetting('link_to_entity'),
44    ];
45
46    return $form;
47  }
48
49  /**
50   * {@inheritdoc}
51   */
52  public function viewElements(FieldItemListInterface $items, $langcode) {
53    $elements = [];
54
55    foreach ($items as $delta => $item) {
56      /** @var $user \Drupal\user\UserInterface */
57      if ($user = $item->getEntity()) {
58        if ($this->getSetting('link_to_entity')) {
59          $elements[$delta] = [
60            '#theme' => 'username',
61            '#account' => $user,
62            '#link_options' => ['attributes' => ['rel' => 'user']],
63            '#cache' => [
64              'tags' => $user->getCacheTags(),
65            ],
66          ];
67        }
68        else {
69          $elements[$delta] = [
70            '#markup' => $user->getDisplayName(),
71            '#cache' => [
72              'tags' => $user->getCacheTags(),
73            ],
74          ];
75        }
76      }
77    }
78
79    return $elements;
80  }
81
82  /**
83   * {@inheritdoc}
84   */
85  public static function isApplicable(FieldDefinitionInterface $field_definition) {
86    return $field_definition->getTargetEntityTypeId() === 'user' && $field_definition->getName() === 'name';
87  }
88
89}
90