protected function AgeFieldFormatter::viewValue in Age Field Formatter 3.0.x
Same name and namespace in other branches
- 8.2 src/Plugin/Field/FieldFormatter/AgeFieldFormatter.php \Drupal\age_field_formatter\Plugin\Field\FieldFormatter\AgeFieldFormatter::viewValue()
- 8 src/Plugin/Field/FieldFormatter/AgeFieldFormatter.php \Drupal\age_field_formatter\Plugin\Field\FieldFormatter\AgeFieldFormatter::viewValue()
Generate the output appropriate for one field item.
Parameters
\Drupal\Core\Field\FieldItemInterface $item: One field item.
Return value
string The textual output generated.
1 call to AgeFieldFormatter::viewValue()
- AgeFieldFormatter::viewElements in src/
Plugin/ Field/ FieldFormatter/ AgeFieldFormatter.php - Builds a renderable array for a field value.
File
- src/
Plugin/ Field/ FieldFormatter/ AgeFieldFormatter.php, line 166
Class
- AgeFieldFormatter
- Plugin implementation of the 'age_field_formatter' formatter.
Namespace
Drupal\age_field_formatter\Plugin\Field\FieldFormatterCode
protected function viewValue(FieldItemInterface $item) {
$from = new DrupalDateTime($item->date);
$to = new DrupalDateTime();
$age = $from
->diff($to)->y;
$agelabel = $this
->t('Age');
$setting = $this
->getSetting('age_format');
$year_suffix = $this
->getSetting('year_suffix');
$format = $this
->getSetting('date_format');
$timezone = $this
->getSetting('timezone_override');
$date_raw = $item
->getValue();
$date = strtotime($date_raw['value']);
$date_formatted = $this->dateFormatter
->format($date, 'custom', $format, $timezone != '' ? $timezone : NULL);
if ($year_suffix == true) {
$age_suffix = $this->stringTranslation
->formatPlural($age, 'year', 'years');
$age = $age . ' ' . $age_suffix;
}
if ($setting == 'birthdate') {
$age_formatted = $date_formatted . " (" . $agelabel . ": " . $age . ")";
}
elseif ($setting == 'birthdate_nolabel') {
$age_formatted = $date_formatted . " (" . $age . ")";
}
else {
$age_formatted = $age;
// We do not force prefix a label to the value.
}
return nl2br(Html::escape($age_formatted));
}