You are here

public function IngredientFormatter::viewElements in Recipe 8.2

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

1 method overrides IngredientFormatter::viewElements()
IngredientRecipeMLFormatter::viewElements in src/Plugin/Field/FieldFormatter/IngredientRecipeMLFormatter.php
Builds a renderable array for a field value.

File

modules/ingredient/src/Plugin/Field/FieldFormatter/IngredientFormatter.php, line 155

Class

IngredientFormatter
Plugin implementation of the 'ingredient_default' formatter.

Namespace

Drupal\ingredient\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $fraction_format = $this
    ->getSetting('fraction_format');
  $output_as_link = $this
    ->getSetting('link');
  $unit_list = $this->ingredientUnitUtility
    ->getConfiguredUnits();
  $elements = [];
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $entity) {

    // Sanitize the name and note.
    $name = Xss::filter($entity
      ->label(), []);
    $note = Xss::filter($items[$delta]->note, []);

    // If the link should be displayed and the entity has a URI, display the
    // link.
    $url = $output_as_link && !$entity
      ->isNew() ? $entity
      ->toUrl() : NULL;
    if ($items[$delta]->quantity > 0) {
      $formatted_quantity = $this->ingredientQuantityUtility
        ->getQuantityFromDecimal($items[$delta]->quantity, $fraction_format);
    }
    else {
      $formatted_quantity = ' ';
    }

    // Print the unit unless it has no abbreviation. Those units do not get
    // printed in any case.
    $unit_name = '';
    $unit_abbreviation = '';
    $unit = isset($unit_list[$items[$delta]->unit_key]) ? $unit_list[$items[$delta]->unit_key] : [];
    if (!empty($unit['abbreviation'])) {
      $unit_name = $items[$delta]->quantity > 1 ? $unit['plural'] : $unit['name'];
      $unit_abbreviation = $unit['abbreviation'];
    }
    $elements[$delta] = [
      '#theme' => 'ingredient_formatter',
      '#ingredient' => $entity,
      '#url' => $url,
      '#name' => $name,
      '#quantity' => $formatted_quantity,
      '#unit_name' => $unit_name,
      '#unit_abbreviation' => $unit_abbreviation,
      '#unit_display' => $this
        ->getSetting('unit_display'),
      '#note' => $note,
    ];
  }
  return $elements;
}