public function DurationHumanDisplayFormatter::viewElements in Duration Field 8
Same name and namespace in other branches
- 8.2 src/Plugin/Field/FieldFormatter/DurationHumanDisplayFormatter.php \Drupal\duration_field\Plugin\Field\FieldFormatter\DurationHumanDisplayFormatter::viewElements()
- 3.0.x src/Plugin/Field/FieldFormatter/DurationHumanDisplayFormatter.php \Drupal\duration_field\Plugin\Field\FieldFormatter\DurationHumanDisplayFormatter::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/ DurationHumanDisplayFormatter.php, line 153
Class
- DurationHumanDisplayFormatter
- Provides a formatter for the duration field type.
Namespace
Drupal\duration_field\Plugin\Field\FieldFormatterCode
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'] && ($years = $duration
->format('%y'))) {
$output[] = $this
->getTimePeriod('year', $years);
}
if ($granularity['month'] && ($months = $duration
->format('%m'))) {
$output[] = $this
->getTimePeriod('month', $months);
}
if ($granularity['day'] && ($days = $duration
->format('%d'))) {
$output[] = $this
->getTimePeriod('day', $days);
}
if ($granularity['hour'] && ($hours = $duration
->format('%h'))) {
$output[] = $this
->getTimePeriod('hour', $hours);
}
if ($granularity['minute'] && ($minutes = $duration
->format('%i'))) {
$output[] = $this
->getTimePeriod('minute', $minutes);
}
if ($granularity['second'] && ($seconds = $duration
->format('%s'))) {
$output[] = $this
->getTimePeriod('second', $seconds);
}
$value = count($output) ? implode($this
->getSeparator(), $output) : '0';
// Render each element as markup.
$element[$delta] = [
'#markup' => $value,
];
}
return $element;
}