You are here

public function UsageLimitFormatter::viewElements in Commerce Core 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

File

modules/promotion/src/Plugin/Field/FieldFormatter/UsageLimitFormatter.php, line 42

Class

UsageLimitFormatter
Plugin implementation of the 'commerce_usage_limit' formatter.

Namespace

Drupal\commerce_promotion\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $field_name = $items
    ->getFieldDefinition()
    ->getName();
  $entity = $items
    ->getEntity();

  // For the "usage_limit" output actual usage / limit.
  if ($field_name === 'usage_limit') {

    // Gets the promotion|coupon usage.
    $current_usage = $entity
      ->getEntityTypeId() === 'commerce_promotion' ? $this->usage
      ->load($entity) : $this->usage
      ->loadByCoupon($entity);
    $usage_limit = $entity
      ->getUsageLimit();
    $usage_limit = $usage_limit ?: $this
      ->t('Unlimited');
    $usage = $current_usage . ' / ' . $usage_limit;
  }
  else {
    $customer_limit = $entity
      ->getCustomerUsageLimit();
    $usage = $customer_limit ?: $this
      ->t('Unlimited');
  }
  $elements[0] = [
    '#markup' => $usage,
  ];
  return $elements;
}