You are here

public function ComputedFormatterBase::viewElements in Computed Field 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/ComputedFormatterBase.php \Drupal\computed_field\Plugin\Field\FieldFormatter\ComputedFormatterBase::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

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

File

src/Plugin/Field/FieldFormatter/ComputedFormatterBase.php, line 25

Class

ComputedFormatterBase
Base class for cached computed fields formatter.

Namespace

Drupal\computed_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  $cache_duration = $this
    ->getSetting('cache_duration');
  $cache_unit = $this
    ->getSetting('cache_unit');
  $elements = [];
  foreach ($items as $delta => $item) {
    if ($cache_unit < 0) {
      $elements[$delta] = [
        '#markup' => $this
          ->prepareValue($item->value),
      ];
    }
    else {
      $elements[$delta] = [
        '#markup' => $this
          ->prepareValue($item
          ->executeCode()),
        '#cache' => [
          'keys' => [
            $items
              ->getEntity()
              ->getEntityTypeId(),
            $items
              ->getEntity()
              ->bundle(),
            $this->viewMode,
          ],
          'max-age' => $cache_duration * $cache_unit,
        ],
      ];
    }
  }
  return $elements;
}