You are here

public function AddToCartController::action in Commerce Add To Cart Link 8

Same name and namespace in other branches
  1. 2.x src/Controller/AddToCartController.php \Drupal\commerce_add_to_cart_link\Controller\AddToCartController::action()

Performs the add to cart action and redirects to cart.

Parameters

\Drupal\commerce_product\Entity\ProductInterface $commerce_product: The product entity.

\Drupal\commerce_product\Entity\ProductVariationInterface $commerce_product_variation: The product variation to add.

string $token: The CSRF token.

\Symfony\Component\HttpFoundation\Request $request: The request.

Return value

\Symfony\Component\HttpFoundation\RedirectResponse A redirect to the cart after adding the product.

Throws

\Exception When the call to self::selectStore() throws an exception because the entity can't be purchased from the current store.

1 string reference to 'AddToCartController::action'
commerce_add_to_cart_link.routing.yml in ./commerce_add_to_cart_link.routing.yml
commerce_add_to_cart_link.routing.yml

File

src/Controller/AddToCartController.php, line 138

Class

AddToCartController
Defines the add to cart controller.

Namespace

Drupal\commerce_add_to_cart_link\Controller

Code

public function action(ProductInterface $commerce_product, ProductVariationInterface $commerce_product_variation, $token, Request $request) {
  $quantity = $request->query
    ->get('quantity', 1);
  $combine = (bool) $request->query
    ->get('combine', 1);
  $order_item = $this->cartManager
    ->createOrderItem($commerce_product_variation, $quantity);
  $store = $this
    ->selectStore($commerce_product_variation);
  $context = new Context($this->currentUser, $store);

  // Explicitly resolve the product price. @todo check necessity after https://www.drupal.org/project/commerce/issues/3088582 has been fixed.
  $resolved_price = $this->chainPriceResolver
    ->resolve($commerce_product_variation, $quantity, $context);
  $order_item
    ->setUnitPrice($resolved_price);
  $order_type_id = $this->orderTypeResolver
    ->resolve($order_item);
  $cart = $this->cartProvider
    ->getCart($order_type_id, $store);
  if (!$cart) {
    $cart = $this->cartProvider
      ->createCart($order_type_id, $store);
  }
  $this->cartManager
    ->addOrderItem($cart, $order_item, $combine);
  return $this
    ->redirect('commerce_cart.page');
}