You are here

public function MeasurementDefaultFormatter::viewElements in Physical Fields 8

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/MeasurementDefaultFormatter.php, line 24

Class

MeasurementDefaultFormatter
Plugin implementation of the 'physical_measurement_default' formatter.

Namespace

Drupal\physical\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $measurement_type = $this->fieldDefinition
    ->getSetting('measurement_type');

  /** @var \Drupal\physical\UnitInterface $unit_class */
  $unit_class = MeasurementType::getUnitClass($measurement_type);
  $unit_labels = $unit_class::getLabels();
  $element = [];

  /** @var \Drupal\physical\Plugin\Field\FieldType\MeasurementItem $item */
  foreach ($items as $delta => $item) {
    $number = $this->numberFormatter
      ->format($item->number);
    $unit = isset($unit_labels[$item->unit]) ? $unit_labels[$item->unit] : $item->unit;
    $element[$delta] = [
      '#markup' => $number . ' ' . $unit,
    ];
  }
  return $element;
}