You are here

public function VariationAddToCartFormatter::viewElements in Commerce Variation Add to Cart 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/VariationAddToCartFormatter.php, line 175

Class

VariationAddToCartFormatter
Plugin implementation of the 'variation_add_to_cart_form' formatter.

Namespace

Drupal\commerce_variation_add_to_cart\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $current_path = $this->currentRequest
    ->getRequestUri();
  $element = [];
  foreach ($items as $delta => $item) {
    $variation = ProductVariation::load($item->target_id);
    $is_active = !empty($variation) ? $variation
      ->isPublished() : FALSE;
    if (!$is_active) {
      continue;
    }
    $product_id = $variation
      ->getProductId();
    $variation_price = $variation
      ->getPrice();
    $variation_price_number = $variation_price
      ->getNumber();
    $variation_price_currency = $variation_price
      ->getCurrencyCode();
    $attributes_values = [];
    $attributes = $variation
      ->getAttributeValueIds();
    foreach ($attributes as $key => $value) {
      $variation_attr = str_replace('attribute_', '', $key);
      $selected_attr = $this
        ->getSetting('attributes');
      if (isset($selected_attr[$variation_attr]) && $selected_attr[$variation_attr] === $variation_attr) {
        $attribute_name = ProductAttributeValue::load($value);
        $attributes_values[] = $attribute_name
          ->getName();
      }
    }
    $element[$delta] = [
      '#theme' => 'variation_add_to_cart_formatter',
      '#variation' => $variation,
      '#product_id' => $product_id,
      '#variation_id' => $item->target_id,
      '#show_title' => $this
        ->getSetting('show_title'),
      '#title' => $variation
        ->getTitle(),
      '#show_price' => $this
        ->getSetting('show_price'),
      '#price_number' => $variation_price_number,
      '#price_format' => $this
        ->getSetting('price_format'),
      '#show_currency' => $this
        ->getSetting('show_currency'),
      '#price_currency' => $variation_price_currency,
      '#show_quantity' => $this
        ->getSetting('show_quantity') == 1 ? 'number' : 'hidden',
      '#attributes' => $attributes_values,
      '#destination' => $current_path,
    ];
  }
  return $element;
}