You are here

public function ColorFieldFormatterCss::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

File

src/Plugin/Field/FieldFormatter/ColorFieldFormatterCss.php, line 218

Class

ColorFieldFormatterCss
Plugin implementation of the color_field css declaration formatter.

Namespace

Drupal\color_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $settings = $this
    ->getSettings();
  $elements = [];
  $entity = $items
    ->getEntity();
  $tokens = [
    $entity
      ->getEntityType()
      ->id() => $entity,
  ];
  foreach ($items as $item) {
    $value = $this
      ->viewValue($item);
    $tokens['color_field'] = $item;
    if ($settings['advanced']) {
      $inline_css = $this->tokenService
        ->replace($settings['css'], $tokens);
    }
    else {
      $selector = $this->tokenService
        ->replace($settings['selector'], $tokens);
      $important = $settings['important'] ? ' !important' : '';
      $property = $settings['property'];
      $inline_css = $selector . ' { ' . $property . ': ' . $value . $important . '; }';
    }
    $elements['#attached']['html_head'][] = [
      [
        '#tag' => 'style',
        '#value' => $inline_css,
      ],
      sha1($inline_css),
    ];
  }
  return $elements;
}