You are here

public function ApStyleDateFieldFormatter::viewElements in AP Style Date 8

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/ApStyleDateFieldFormatter.php, line 256

Class

ApStyleDateFieldFormatter
Plugin implementation of the 'timestamp' formatter as time ago.

Namespace

Drupal\date_ap_style\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $opts = [
    'always_display_year',
    'display_day',
    'use_today',
    'cap_today',
    'display_time',
    'time_before_date',
    'use_all_day',
    'display_noon_and_midnight',
    'capitalize_noon_and_midnight',
  ];
  $options = [];
  foreach ($opts as $opt) {
    if ($this
      ->getSetting($opt)) {
      $options[$opt] = TRUE;
    }
  }
  $timezone = $this
    ->getSetting('timezone') ?: NULL;
  $field_type = $items
    ->getFieldDefinition()
    ->getType();
  foreach ($items as $delta => $item) {
    if ($field_type == 'datetime') {
      $timestamp = $item->date
        ->getTimestamp();
    }
    else {
      $timestamp = $item->value;
    }
    $elements[$delta] = [
      '#cache' => [
        'contexts' => [
          'timezone',
        ],
      ],
      '#markup' => $this->apStyleDateFormatter
        ->formatTimestamp($timestamp, $options, $timezone, $langcode),
    ];
  }
  return $elements;
}