You are here

public function ExpandCollapseFormatter::viewElements in Expand collapse 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/ExpandCollapseFormatter.php, line 116
Contains the ExpandCollapseFormatter class.

Class

ExpandCollapseFormatter
The expand collapse formatter.

Namespace

Drupal\expand_collapse_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];
  foreach ($items as $delta => $item) {
    if ($item->processed != NULL) {
      $output = $item->processed;
    }
    else {
      $output = $item->value;
    }

    // Render each element as markup.
    $element[$delta] = [
      '#theme' => 'expand_collapse_formatter',
      '#value' => $output,
      '#trim_length' => $this
        ->getSetting('trim_length'),
      '#default_state' => $this
        ->getSetting('default_state'),
      '#link_text_open' => $this
        ->getSetting('link_text_open'),
      '#link_text_close' => $this
        ->getSetting('link_text_close'),
      '#link_class_open' => $this
        ->getSetting('link_class_open'),
      '#link_class_close' => $this
        ->getSetting('link_class_close'),
      '#attached' => [
        'library' => [
          'expand_collapse_formatter/expand_collapse_formatter',
        ],
      ],
    ];
  }
  return $element;
}