You are here

public function LinkedAndWrapped::viewElements in Title 8.2

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/LinkedAndWrapped.php, line 27

Class

LinkedAndWrapped
A field formatter for linking and wrapping text.

Namespace

Drupal\title\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  $output = [];
  $attributes = new Attribute();
  if ($this
    ->getSetting('tag') == 'h1') {
    $attributes
      ->addClass('title');
    $attributes
      ->addClass('replaced-title');
    $attributes
      ->setAttribute('id', 'page-title');
  }
  $classes = $this
    ->getSetting('classes');
  if (!empty($classes)) {
    $attributes
      ->addClass($classes);
  }
  $parent = $items
    ->getParent()
    ->getValue();
  foreach ($items as $item) {
    $text = $item
      ->getValue()['value'];
    if ($this
      ->getSetting('linked')) {
      $text = Link::fromTextAndUrl($text, $parent
        ->toUrl())
        ->toString();
    }
    $output[] = [
      '#type' => 'html_tag',
      '#tag' => $this
        ->getSetting('tag'),
      '#attributes' => $attributes
        ->toArray(),
      '#value' => $text,
    ];
  }
  return $output;
}