You are here

public function IngredientRecipeMLFormatter::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 IngredientFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/IngredientRecipeMLFormatter.php, line 57

Class

IngredientRecipeMLFormatter
Plugin implementation of the 'ingredient_recipeml' formatter.

Namespace

Drupal\recipe\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $fraction_format = $this
    ->getSetting('fraction_format');
  $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 ($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_recipeml_formatter',
      '#name' => $name,
      '#quantity' => $formatted_quantity,
      '#unit_name' => $unit_name,
      '#unit_abbreviation' => $unit_abbreviation,
      '#unit_display' => $this
        ->getSetting('unit_abbreviation'),
      '#note' => $note,
    ];
  }
  return $elements;
}