You are here

public function ListStringListClassFormatter::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 ElementListClassTrait::viewElements

File

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

Class

ListStringListClassFormatter
Formatter for displaying list (text) in an HTML list.

Namespace

Drupal\element_class_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  if ($items
    ->isEmpty()) {
    return [];
  }
  $elements = [];
  $attributes = new Attribute();
  $class = $this
    ->getSetting('class');
  if (!empty($class)) {
    $attributes
      ->addClass($class);
  }
  $field_storage = $items
    ->getFieldDefinition()
    ->getFieldStorageDefinition();
  $options = options_allowed_values($field_storage);
  foreach ($items as $delta => $item) {
    $elements[$delta] = $options[$item
      ->getValue()['value']];
  }
  return [
    [
      '#theme' => 'item_list',
      '#items' => $elements,
      '#list_type' => $this
        ->getSetting('list_type'),
      '#attributes' => $attributes
        ->toArray(),
    ],
  ];
}