3 namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
7 use Drupal\Core\Field\FieldItemListInterface;
8 use Drupal\Core\Form\FormStateInterface;
11 * Plugin implementation of the 'entity reference label' formatter.
14 * id = "entity_reference_label",
15 * label = @Translation("Label"),
16 * description = @Translation("Display the label of the referenced entities."),
22 class EntityReferenceLabelFormatter extends EntityReferenceFormatterBase {
27 public static function defaultSettings() {
30 ] + parent::defaultSettings();
36 public function settingsForm(array $form, FormStateInterface $form_state) {
38 '#title' => t('Link label to the referenced entity'),
39 '#type' => 'checkbox',
40 '#default_value' => $this->getSetting('link'),
49 public function settingsSummary() {
51 $summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link');
58 public function viewElements(FieldItemListInterface $items, $langcode) {
60 $output_as_link = $this->getSetting('link');
62 foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
63 $label = $entity->label();
64 // If the link is to be displayed and the entity has a uri, display a
66 if ($output_as_link && !$entity->isNew()) {
68 $uri = $entity->urlInfo();
70 catch (UndefinedLinkTemplateException $e) {
71 // This exception is thrown by \Drupal\Core\Entity\Entity::urlInfo()
72 // and it means that the entity type doesn't have a link template nor
73 // a valid "uri_callback", so don't bother trying to output a link for
74 // the rest of the referenced entities.
75 $output_as_link = FALSE;
79 if ($output_as_link && isset($uri) && !$entity->isNew()) {
84 '#options' => $uri->getOptions(),
87 if (!empty($items[$delta]->_attributes)) {
88 $elements[$delta]['#options'] += ['attributes' => []];
89 $elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
90 // Unset field item attributes since they have been included in the
91 // formatter output and shouldn't be rendered in the field template.
92 unset($items[$delta]->_attributes);
96 $elements[$delta] = ['#plain_text' => $label];
98 $elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
107 protected function checkAccess(EntityInterface $entity) {
108 return $entity->access('view label', NULL, TRUE);