You are here

public function AddToCart::viewElements in Commerce Cart Flyout 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/AddToCart.php, line 171

Class

AddToCart
Plugin implementation of the 'commerce_cart_flyout_add_to_cart' formatter.

Namespace

Drupal\commerce_cart_flyout\Plugin\Field\FieldFormatter

Code

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

  /** @var \Drupal\commerce_product\Entity\ProductInterface $product */
  $product = $items
    ->getEntity();

  // If we could not load a default variation, just bail.
  $default_variation = $this->variationStorage
    ->loadFromContext($product);
  if (!$default_variation) {
    return [];
  }
  $order_item = $this->orderItemStorage
    ->createFromPurchasableEntity($default_variation);
  $form_display = EntityFormDisplay::collectRenderDisplay($order_item, 'add_to_cart');
  $purchased_entity_widget = $form_display
    ->getComponent('purchased_entity');
  $variations = $this
    ->loadVariations($product);

  // Fake a requirement on the current route so that our Normalizers run.
  $this->routeMatch
    ->getRouteObject()
    ->setRequirement('_cart_api', 'true');
  $elements = [];
  $elements[0]['add_to_cart_form'] = [
    '#attached' => [
      'library' => [
        'core/drupalSettings',
        'commerce_cart_flyout/add_to_cart',
      ],
      'drupalSettings' => [
        'addToCart' => [
          $product
            ->uuid() => [
            'defaultVariation' => $default_variation
              ->uuid(),
            'variations' => $this->serializer
              ->normalize($variations),
            'injectedFields' => $this
              ->getVariationInjectedFields($variations),
            'type' => $purchased_entity_widget['type'],
          ],
        ],
        'theme' => [
          'commerce_cart_flyout_add_to_cart_button' => $this
            ->renderTemplate('commerce_cart_flyout_add_to_cart_button'),
          'commerce_cart_flyout_add_to_cart_variation_select' => $this
            ->renderTemplate('commerce_cart_flyout_add_to_cart_variation_select'),
        ],
      ],
    ],
    '#markup' => Markup::create(sprintf('<div %s></div>', new Attribute([
      'data-product' => $product
        ->uuid(),
      'data-view-mode' => $this->viewMode,
      'data-langcode' => $langcode,
    ]))),
  ];
  if ($purchased_entity_widget['type'] === 'commerce_product_variation_attributes') {
    foreach ($variations as $variation) {
      $prepared_attributes = $this->attributeMapper
        ->prepareAttributes($variation, $variations);
      $prepared_attributes = array_filter($prepared_attributes, static function (PreparedAttribute $prepared_attribute) {

        // There will always be at least one value, possibly `_none`.
        // If we have more than one value, allow the prepared attribute. But if
        // we only have one, do not consider it, if it is the `_none` value.
        $values = $prepared_attribute
          ->getValues();
        return count($values) > 1 || !isset($values['_none']);
      });
      $elements[0]['add_to_cart_form']['#attached']['library'][] = 'commerce_product/rendered-attributes';
      $elements[0]['add_to_cart_form']['#attached']['drupalSettings']['addToCart'][$product
        ->uuid()]['attributeOptions'][$variation
        ->uuid()] = [
        'attributes' => $this->serializer
          ->normalize(array_values($prepared_attributes)),
        'renderedAttributes' => $this
          ->renderPreparedAttributes($prepared_attributes),
      ];
    }
    $elements[0]['add_to_cart_form']['#attached']['drupalSettings']['theme'] += [
      'commerce_cart_flyout_add_to_cart_attributes_select' => $this
        ->renderTemplate('commerce_cart_flyout_add_to_cart_attributes_select'),
      'commerce_cart_flyout_add_to_cart_attributes_radios' => $this
        ->renderTemplate('commerce_cart_flyout_add_to_cart_attributes_radios'),
      'commerce_cart_flyout_add_to_cart_attributes_rendered' => $this
        ->renderTemplate('commerce_cart_flyout_add_to_cart_attributes_rendered'),
    ];
  }
  $cacheability = new CacheableMetadata();
  $cacheability
    ->addCacheableDependency($order_item);
  $cacheability
    ->addCacheableDependency($form_display);
  $cacheability
    ->addCacheableDependency($product);
  foreach ($variations as $variation) {
    $cacheability
      ->addCacheableDependency($variation);
  }
  $cacheability
    ->applyTo($elements);
  return $elements;
}