You are here

public function ColorFieldFormatterSwatchOptions::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 ColorFieldFormatterSwatch::viewElements

File

src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatchOptions.php, line 28

Class

ColorFieldFormatterSwatchOptions
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 = [];
  $name = Html::getUniqueId("color-field");
  foreach ($items as $delta => $item) {
    $hex = $this
      ->viewRawValue($item);
    $id = Html::getUniqueId("color-field-{$hex}");
    $elements[$delta] = [
      '#theme' => 'color_field_formatter_swatch_option',
      '#id' => $id,
      '#name' => $name,
      '#input_type' => $this->fieldDefinition
        ->getFieldStorageDefinition()
        ->isMultiple() ? 'checkbox' : 'radio',
      '#value' => $hex,
      '#shape' => $settings['shape'],
      '#height' => is_numeric($settings['height']) ? "{$settings['height']}px" : $settings['height'],
      '#width' => is_numeric($settings['width']) ? "{$settings['width']}px" : $settings['width'],
      '#color' => $this
        ->viewValue($item),
      '#attributes' => new Attribute([
        'class' => [
          "color_field__swatch--{$settings['shape']}",
        ],
      ]),
    ];
    if ($settings['data_attribute']) {
      $elements[$delta]['#attributes']['data-color'] = $hex;
    }
  }
  return $elements;
}