You are here

public function DateRangePlainFormatter::viewElements in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/datetime_range/src/Plugin/Field/FieldFormatter/DateRangePlainFormatter.php \Drupal\datetime_range\Plugin\Field\FieldFormatter\DateRangePlainFormatter::viewElements()
  2. 9 core/modules/datetime_range/src/Plugin/Field/FieldFormatter/DateRangePlainFormatter.php \Drupal\datetime_range\Plugin\Field\FieldFormatter\DateRangePlainFormatter::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 DateTimeRangeTrait::viewElements

File

core/modules/datetime_range/src/Plugin/Field/FieldFormatter/DateRangePlainFormatter.php, line 40

Class

DateRangePlainFormatter
Plugin implementation of the 'Plain' formatter for 'daterange' fields.

Namespace

Drupal\datetime_range\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $separator = $this
    ->getSetting('separator');
  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;
      if ($start_date
        ->getTimestamp() !== $end_date
        ->getTimestamp()) {
        $elements[$delta] = [
          'start_date' => $this
            ->buildDate($start_date),
          'separator' => [
            '#plain_text' => ' ' . $separator . ' ',
          ],
          'end_date' => $this
            ->buildDate($end_date),
        ];
      }
      else {
        $elements[$delta] = $this
          ->buildDate($start_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;
}