function ColorBackgroudFormatter::viewElements

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

modules/field_example/src/Plugin/Field/FieldFormatter/ColorBackgroudFormatter.php, line 31

Class

ColorBackgroudFormatter
Plugin implementation of the 'field_example_color_background' formatter.

Namespace

Drupal\field_example\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    // Set the value of the CSS color property depending on user provided
    // configuration. Individual configuration items can be accessed with
    // $this->getSetting('key') where 'key' is the same as the key in the
    // form array from settingsForm() and what's defined in the configuration
    // schema.
    $text_color = 'inherit';
    if ($this->getSetting('adjust_text_color')) {
      $text_color = $this->lightness($item->value) < 50 ? 'white' : 'black';
    }
    $elements[$delta] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#value' => $this->t('The content area color has been changed to @code', [
        '@code' => $item->value,
      ]),
      '#attributes' => [
        'style' => 'background-color: ' . $item->value . '; color: ' . $text_color,
      ],
    ];
  }
  return $elements;
}