You are here

public function PadoAddToCartForm::submitForm in Commerce Product Add-on 8

This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state can be updated, this way the subsequently invoked handlers can retrieve a regular entity object to act on. Generally this method should not be overridden unless the entity requires the same preparation for two actions, see \Drupal\comment\CommentForm for an example with the save and preview actions.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides AddToCartForm::submitForm

File

src/Form/PadoAddToCartForm.php, line 129

Class

PadoAddToCartForm
Provides the order item add to cart form.

Namespace

Drupal\commerce_pado\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $add_ons = $form_state
    ->getValue([
    'add_ons',
    'items',
  ]) ?: [];
  $combine = $form_state
    ->get([
    'settings',
    'combine',
  ]);
  $add_ons = array_filter($add_ons);
  $variation_ids = [];
  foreach ($add_ons as $add_on_group) {
    if (is_array($add_on_group)) {
      foreach ($add_on_group as $variation_id) {
        $variation_ids[] = $variation_id;
      }
    }
    else {
      $variation_ids[] = $add_on_group;
    }
  }
  $add_on_variations = $this->entityTypeManager
    ->getStorage('commerce_product_variation')
    ->loadMultiple($variation_ids);
  $cart = $this->entityTypeManager
    ->getStorage('commerce_order')
    ->load($form_state
    ->get('cart_id'));

  /** @var \Drupal\commerce_product\Entity\ProductVariation $add_on_variation */
  foreach ($add_on_variations as $add_on_variation) {

    // @todo Allow providing quantity in the add to cart form.
    $order_item = $this->cartManager
      ->createOrderItem($add_on_variation);
    $store = $this
      ->selectStore($add_on_variation);
    $context = new Context($this->currentUser, $store);
    $resolved_price = $this->chainPriceResolver
      ->resolve($add_on_variation, 1, $context);
    $order_item
      ->setTitle($add_on_variation
      ->getOrderItemTitle());
    $order_item
      ->setUnitPrice($resolved_price);
    $this->cartManager
      ->addOrderItem($cart, $order_item, $combine);
    $this
      ->messenger()
      ->addMessage($this
      ->t('@entity added to @cart-link.', [
      '@entity' => $add_on_variation
        ->label(),
      '@cart-link' => Link::createFromRoute($this
        ->t('your cart', [], [
        'context' => 'cart link',
      ]), 'commerce_cart.page')
        ->toString(),
    ]));
  }
}