You are here

public function SimpleTextFormatter::viewElements in Examples for Developers 8

Same name in this branch
  1. 8 field_example/src/Plugin/Field/FieldFormatter/SimpleTextFormatter.php \Drupal\field_example\Plugin\Field\FieldFormatter\SimpleTextFormatter::viewElements()
  2. 8 field_permission_example/src/Plugin/Field/FieldFormatter/SimpleTextFormatter.php \Drupal\field_permission_example\Plugin\Field\FieldFormatter\SimpleTextFormatter::viewElements()
Same name and namespace in other branches
  1. 3.x modules/field_example/src/Plugin/Field/FieldFormatter/SimpleTextFormatter.php \Drupal\field_example\Plugin\Field\FieldFormatter\SimpleTextFormatter::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

field_example/src/Plugin/Field/FieldFormatter/SimpleTextFormatter.php, line 25

Class

SimpleTextFormatter
Plugin implementation of the 'field_example_simple_text' formatter.

Namespace

Drupal\field_example\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    $elements[$delta] = [
      // We create a render array to produce the desired markup,
      // "<p style="color: #hexcolor">The color code ... #hexcolor</p>".
      // See theme_html_tag().
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#attributes' => [
        'style' => 'color: ' . $item->value,
      ],
      '#value' => $this
        ->t('The color code in this field is @code', [
        '@code' => $item->value,
      ]),
    ];
  }
  return $elements;
}