You are here

public function LinkAllyFormatter::viewElements in Element Class Formatter 8

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

src/Plugin/Field/FieldFormatter/LinkAllyFormatter.php, line 125

Class

LinkAllyFormatter
Defines a formatter that allows links with screenreader only text.

Namespace

Drupal\element_class_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $build = [];
  $entity = $items
    ->getEntity();
  $custom_link_text = $this
    ->getSetting('link_text');
  $cache = new BubbleableMetadata();
  $screenreader_text = trim($this->token
    ->replace($this
    ->getSetting('screenreader_text'), [
    $entity
      ->getEntityTypeId() => $entity,
  ], [], $cache));
  if ($screenreader_text) {
    $screenreader_text = [
      '#type' => 'inline_template',
      '#template' => '<span class="visually-hidden">{{screenreader_text}}</span>',
      '#context' => [
        'screenreader_text' => [
          '#markup' => $screenreader_text,
        ],
      ],
    ];
  }
  foreach ($items as $delta => $item) {
    $label = $items
      ->getFieldDefinition()
      ->getType() === 'link' ? $item->title : $item->value;
    $uri = $items
      ->getFieldDefinition()
      ->getType() === 'link' ? $item
      ->getUrl() ?: Url::fromRoute('<none>') : $entity
      ->toUrl('canonical');
    if ($custom_link_text) {
      $label = $custom_link_text;
    }
    if ($screenreader_text) {
      $label = [
        [
          '#plain_text' => $label,
        ],
        $screenreader_text,
      ];
    }
    $build[$delta] = [
      '#type' => 'link',
      '#title' => $label,
      '#url' => $uri,
      '#options' => $uri
        ->getOptions(),
    ];
  }
  $cache
    ->applyTo($build);
  $build = $this
    ->setElementClass($build, $this
    ->getSetting('class'), $items);
  if ($tag = $this
    ->getSetting('tag')) {
    foreach (Element::children($build) as $delta) {
      $build[$delta] = [
        '#type' => 'inline_template',
        '#template' => '<{{tag}}>{{element}}</{{tag}}>',
        '#context' => [
          'tag' => $tag,
          'element' => $build[$delta],
        ],
      ];
    }
  }
  return $build;
}