You are here

public function StoreDateTimeFormatter::viewElements in Commerce Core 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

modules/store/src/Plugin/Field/FieldFormatter/StoreDateTimeFormatter.php, line 149

Class

StoreDateTimeFormatter
Plugin implementation of the 'commerce_store_datetime' formatter.

Namespace

Drupal\commerce_store\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $date_pattern = $this
    ->getDateFormat()
    ->getPattern();
  $timezone = $this
    ->getTimezone();
  $store = $this->currentStore
    ->getStore();
  $elements = [];
  foreach ($items as $delta => $item) {
    if ($item->value) {
      $date = new DrupalDateTime($item->value, $timezone);
      $elements[$delta] = [
        '#theme' => 'time',
        '#text' => $date
          ->format($date_pattern),
        '#html' => FALSE,
        '#attributes' => [
          'datetime' => $date
            ->format('Y-m-d\\TH:i:sP'),
        ],
        '#cache' => [
          'contexts' => [
            'store',
          ],
        ],
      ];
      if ($store) {

        // Make sure the render cache is cleared when the store is updated.
        $cacheability = new CacheableMetadata();
        $cacheability
          ->addCacheableDependency($store);
        $cacheability
          ->applyTo($elements[$delta]);
      }
      if (!empty($item->_attributes)) {
        $elements[$delta]['#attributes'] += $item->_attributes;

        // Unset field item attributes since they have been included in the
        // formatter output and should not be rendered in the field template.
        unset($item->_attributes);
      }
    }
  }
  return $elements;
}