You are here

public function ApStyleDateRangeFieldFormatter::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 DateTimeRangeTrait::viewElements

File

src/Plugin/Field/FieldFormatter/ApStyleDateRangeFieldFormatter.php, line 266

Class

ApStyleDateRangeFieldFormatter
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;
  foreach ($items as $delta => $item) {
    if (!empty($item->start_date) && !empty($item->end_date)) {

      /** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
      $start_date = $item->start_date;

      /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
      $end_date = $item->end_date;
      $dates['start'] = $start_date
        ->getTimestamp();
      $dates['end'] = $end_date
        ->getTimestamp();
      $elements[$delta] = [
        '#cache' => [
          'contexts' => [
            'timezone',
          ],
        ],
        '#markup' => $this->apStyleDateFormatter
          ->formatRange($dates, $options, $timezone, $langcode),
      ];
    }
  }
  return $elements;
}