public function DateTimeDefaultFormatter::viewElements

Builds a renderable array for a field value.

Parameters

Drupal\Core\Entity\EntityInterface $entity: The entity being displayed.

string $langcode: The language associated with $items.

array $items: Array of values for this field.

Return value

array A renderable array for $items, as an array of child elements keyed by numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

drupal/core/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimeDefaultFormatter.php, line 37
Contains \Drupal\datetime\Plugin\field\formatter\DateTimeDefaultFormatter.

Class

DateTimeDefaultFormatter
Plugin implementation of the 'datetime_default' formatter.

Namespace

Drupal\datetime\Plugin\field\formatter

Code

public function viewElements(EntityInterface $entity, $langcode, array $items) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $formatted_date = '';
    $iso_date = '';
    if (!empty($item['date'])) {

      // The date was created and verified during field_load(), so it is safe
      // to use without further inspection.
      $date = $item['date'];

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

      // The formatted output will be in local time.
      $date
        ->setTimeZone(timezone_open(drupal_get_user_timezone()));
      if ($this->field['settings']['datetime_type'] == 'date') {

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

    // Display the date using theme datetime.
    // @todo How should RDFa attributes be added to this?
    $elements[$delta] = array(
      '#theme' => 'datetime',
      '#text' => $formatted_date,
      '#html' => FALSE,
      '#attributes' => array(
        'datetime' => $iso_date,
        'property' => array(
          'dc:date',
        ),
        'datatype' => 'xsd:dateTime',
      ),
    );
  }
  return $elements;
}