You are here

public function VariationAddToCart::addItem in Commerce Variation Add to Cart 8

Add item to cart.

1 string reference to 'VariationAddToCart::addItem'
commerce_variation_add_to_cart.routing.yml in ./commerce_variation_add_to_cart.routing.yml
commerce_variation_add_to_cart.routing.yml

File

src/Controller/VariationAddToCart.php, line 84

Class

VariationAddToCart
Variation add to cart form controller.

Namespace

Drupal\commerce_variation_add_to_cart\Controller

Code

public function addItem() {

  // Get item data from post request.
  $product_id = (int) $this->currentRequest->request
    ->get('product_id');
  $variation_id = (int) $this->currentRequest->request
    ->get('variation_id');
  $quantity = (int) $this->currentRequest->request
    ->get('quantity');
  $destination = $this->currentRequest->request
    ->get('destination');
  if (empty($destination)) {
    $destination = '/cart';
  }
  if ($product_id > 0 && $variation_id > 0 && $quantity > 0) {

    // Load product variation and get store.
    $variation = ProductVariation::load($variation_id);
    $variation_price = $variation
      ->getPrice();
    $stores = $variation
      ->getStores();
    $store = reset($stores);
    $all_carts = $this->cartProvider
      ->getCarts();
    $cart = reset($all_carts);

    // Create cart for user if it already doesn't exist.
    if (!$cart) {
      $cart = $this->cartProvider
        ->createCart('default', $store);
    }
    $order_item = OrderItem::create([
      'type' => 'default',
      'purchased_entity' => (string) $variation_id,
      'quantity' => $quantity,
      'unit_price' => $variation_price,
    ]);
    $order_item
      ->save();
    $this->cartManager
      ->addOrderItem($cart, $order_item);
    return new RedirectResponse($destination);
  }
  $this
    ->messenger()
    ->addMessage($this
    ->t('Product not added to your cart.'), 'error', TRUE);
  return new RedirectResponse($destination);
}