You are here

public function DurationTimeFormatter::viewElements in Duration Field 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/DurationTimeFormatter.php \Drupal\duration_field\Plugin\Field\FieldFormatter\DurationTimeFormatter::viewElements()
  2. 3.0.x src/Plugin/Field/FieldFormatter/DurationTimeFormatter.php \Drupal\duration_field\Plugin\Field\FieldFormatter\DurationTimeFormatter::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

src/Plugin/Field/FieldFormatter/DurationTimeFormatter.php, line 36

Class

DurationTimeFormatter
Provides a formatter for the duration field type.

Namespace

Drupal\duration_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];
  $granularity = $this
    ->getFieldSetting('granularity');
  foreach ($items as $delta => $item) {
    $duration = new \DateInterval($item->value);
    $output = [];
    if ($granularity['year'] || $granularity['month'] || $granularity['day']) {
      $output[] = $duration
        ->format('%y') . '-' . $duration
        ->format('%m') . '-' . $duration
        ->format('%d');
    }
    if ($granularity['hour'] || $granularity['minute'] || $granularity['second']) {
      $output[] = $duration
        ->format('%h') . ':' . $duration
        ->format('%I') . ':' . $duration
        ->format('%S');
    }

    // Render each element as markup.
    $element[$delta] = [
      '#markup' => implode(' ', $output),
    ];
  }
  return $element;
}