You are here

public function ColorFieldFormatterSwatch::viewElements in Color Field 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

1 method overrides ColorFieldFormatterSwatch::viewElements()
ColorFieldFormatterSwatchOptions::viewElements in src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatchOptions.php
Builds a renderable array for a field value.

File

src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatch.php, line 141

Class

ColorFieldFormatterSwatch
Plugin implementation of the color_field swatch formatter.

Namespace

Drupal\color_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $settings = $this
    ->getSettings();
  $elements = [];
  $elements['#attached']['library'][] = 'color_field/color-field-formatter-swatch';
  foreach ($items as $delta => $item) {
    $elements[$delta] = [
      '#theme' => 'color_field_formatter_swatch',
      '#color' => $this
        ->viewValue($item),
      '#shape' => $settings['shape'],
      '#width' => is_numeric($settings['width']) ? "{$settings['width']}px" : $settings['width'],
      '#height' => is_numeric($settings['height']) ? "{$settings['height']}px" : $settings['height'],
      '#attributes' => new Attribute([
        'class' => [
          'color_field__swatch',
          "color_field__swatch--{$settings['shape']}",
        ],
      ]),
    ];
    if ($settings['data_attribute']) {
      $color = new ColorHex($item->color, $item->opacity);
      $elements[$delta]['#attributes']['data-color'] = $color
        ->toString(FALSE);
    }
  }
  return $elements;
}