You are here

public function SimpleStockLevelFormatter::viewElements in Commerce Stock 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

modules/field/src/Plugin/Field/FieldFormatter/SimpleStockLevelFormatter.php, line 74

Class

SimpleStockLevelFormatter
Plugin implementation of the 'commerce_stock_level_simple' formatter.

Namespace

Drupal\commerce_stock_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {

  // Get the entity.
  $entity = $items
    ->getEntity();
  if ($entity instanceof PurchasableEntityInterface) {

    // Get the available Stock for the product variation.
    $stockServiceManager = $this->stockServiceManager;
    $level = $stockServiceManager
      ->getStockLevel($entity);
  }
  else {

    // No stock if this is not a purchasable entity.
    $level = 0;
  }
  $elements = [];

  // Return a single item.
  $elements[0] = [
    '#type' => 'html_tag',
    '#tag' => 'p',
    '#value' => $level,
  ];
  return $elements;
}