You are here

public function TitleFormatter::viewElements in Manage display 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 BasicStringFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/TitleFormatter.php, line 27

Class

TitleFormatter
A field formatter for entity titles.

Namespace

Drupal\manage_display\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  $output = [];
  $parent = $items
    ->getParent()
    ->getValue();
  foreach ($items as $item) {
    $text = $item
      ->getValue()['value'];
    if ($this
      ->getSetting('linked') && $this
      ->canLink()) {

      // When previewing a new entity, there is no URL. It gives a better
      // preview if we still show a link, so use <front>.
      $url = $parent
        ->isNew() ? Url::fromRoute('<front>') : $parent
        ->toUrl();
      $text = Link::fromTextAndUrl($text, $url)
        ->toString();
    }
    $output[] = [
      '#type' => 'html_tag',
      '#tag' => $this
        ->getSetting('tag'),
      '#value' => $text,
    ];
  }
  return $output;
}