3 namespace Drupal\user\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\FormatterBase;
8 use Drupal\Core\Form\FormStateInterface;
11 * Plugin implementation of the 'user_name' formatter.
15 * label = @Translation("User name"),
16 * description = @Translation("Display the user or author name."),
22 class UserNameFormatter extends FormatterBase {
27 public static function defaultSettings() {
28 $options = parent::defaultSettings();
30 $options['link_to_entity'] = TRUE;
37 public function settingsForm(array $form, FormStateInterface $form_state) {
38 $form = parent::settingsForm($form, $form_state);
40 $form['link_to_entity'] = [
41 '#type' => 'checkbox',
42 '#title' => $this->t('Link to the user'),
43 '#default_value' => $this->getSetting('link_to_entity'),
52 public function viewElements(FieldItemListInterface $items, $langcode) {
55 foreach ($items as $delta => $item) {
56 /** @var $user \Drupal\user\UserInterface */
57 if ($user = $item->getEntity()) {
58 if ($this->getSetting('link_to_entity')) {
60 '#theme' => 'username',
62 '#link_options' => ['attributes' => ['rel' => 'user']],
64 'tags' => $user->getCacheTags(),
70 '#markup' => $user->getDisplayName(),
72 'tags' => $user->getCacheTags(),
85 public static function isApplicable(FieldDefinitionInterface $field_definition) {
86 return $field_definition->getTargetEntityTypeId() === 'user' && $field_definition->getName() === 'name';