You are here

public function WrapperClassFormatter::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/WrapperClassFormatter.php, line 137

Class

WrapperClassFormatter
A field formatter for wrapping text with a class.

Namespace

Drupal\element_class_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  $elements = [];
  $attributes = new Attribute();
  $class = $this
    ->getSetting('class');
  if (!empty($class)) {
    $attributes
      ->addClass($class);
  }
  $parent = $items
    ->getParent()
    ->getValue();
  foreach ($items as $delta => $item) {
    if (!empty($item->format)) {
      $text = [
        '#type' => 'processed_text',
        '#text' => $item->value,
        '#format' => $item->format,
        '#langcode' => $item
          ->getLangcode(),
      ];
    }
    else {
      $text = [
        '#type' => 'inline_template',
        '#template' => '{{ value|nl2br }}',
        '#context' => [
          'value' => $item->value,
        ],
      ];
    }
    if ($this
      ->getSetting('summary')) {
      $text = [
        '#plain_text' => !empty($item->summary) ? strip_tags($item->summary) : text_summary(strip_tags($item->value), 'plain_text', $this
          ->getSetting('trim')),
      ];
    }
    $text = render($text);
    if ($this
      ->getSetting('link') && $parent instanceof EntityInterface) {
      $link_attributes = new Attribute();
      $link_class = $this
        ->getSetting('link_class');
      if (!empty($link_class)) {
        $link_attributes
          ->addClass($link_class);
      }
      $link = Link::fromTextAndUrl($text, $parent
        ->toUrl())
        ->toRenderable();
      $link['#attributes'] = $link_attributes
        ->toArray();
      $text = render($link);
    }
    $elements[$delta] = [
      '#type' => 'html_tag',
      '#tag' => $this
        ->getSetting('tag'),
      '#attributes' => $attributes
        ->toArray(),
      '#value' => $text,
    ];
  }
  return $elements;
}