You are here

protected function AgeFieldFormatter::viewValue in Age Field Formatter 8

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

Class

AgeFieldFormatter
Plugin implementation of the 'age_field_formatter' formatter.

Namespace

Drupal\age_field_formatter\Plugin\Field\FieldFormatter

Code

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');
  if ($year_suffix == true) {
    $age_suffix = $this->stringTranslation
      ->formatPlural($age, 'year', 'years');
    $age = $age . ' ' . $age_suffix;
  }
  if ($setting == 'birthdate') {
    $age_formatted = $item->value . " (" . $agelabel . ": " . $age . ")";
  }
  elseif ($setting == 'birthdate_nolabel') {
    $age_formatted = $item->value . " (" . $age . ")";
  }
  else {
    $age_formatted = $age;

    // We do not force prefix a label to the value.
  }
  return nl2br(Html::escape($age_formatted));
}