You are here

public function DateTimeDefaultFormatter::viewElements in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php \Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeDefaultFormatter::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

core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeDefaultFormatter.php, line 39
Contains \Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeDefaultFormatter.

Class

DateTimeDefaultFormatter
Plugin implementation of the 'Default' formatter for 'datetime' fields.

Namespace

Drupal\datetime\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $output = '';
    $iso_date = '';
    if ($item->date) {

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

      // Create the ISO date in Universal Time.
      $iso_date = $date
        ->format("Y-m-d\\TH:i:s") . 'Z';
      if ($this
        ->getFieldSetting('datetime_type') == 'date') {

        // A date without time will pick up the current time, use the default.
        datetime_date_default_time($date);
      }
      $this
        ->setTimeZone($date);
      $output = $this
        ->formatDate($date);
    }

    // Display the date using theme datetime.
    $elements[$delta] = array(
      '#cache' => [
        'contexts' => [
          'timezone',
        ],
      ],
      '#theme' => 'time',
      '#text' => $output,
      '#html' => FALSE,
      '#attributes' => array(
        'datetime' => $iso_date,
      ),
    );
    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;
}