2

I want to empty the cart before a product in the code. I tried

$this->cartProvider->emptyCart($cart);

But this did not work and gave an error. I am doing this in Drupal 8. I am adding products in the controller code.

This is how I am fetching the cart.

$destination = \Drupal::service('path.current')->getPath();
   $productObj = Product::load($productId);

   $product_variation_id = $productObj->get('variations')
     ->getValue()[0]['target_id'];
   $storeId = $productObj->get('stores')->getValue()[0]['target_id'];
   $variationobj = \Drupal::entityTypeManager()
     ->getStorage('commerce_product_variation')
     ->load($product_variation_id);
   $store = \Drupal::entityTypeManager()
     ->getStorage('commerce_store')
     ->load($storeId);



     $cart = $this->cartProvider->getCart('default', $store);

     $this->cartManager->emptyCart($cart);

   if (!$cart) {
    $cart = $this->cartProvider->createCart('default', $store);

   }

   $line_item_type_storage = \Drupal::entityTypeManager()
     ->getStorage('commerce_order_item_type');
// Process to place order programatically.
   $cart_manager = \Drupal::service('commerce_cart.cart_manager');
   $line_item = $cart_manager->addEntity($cart, $variationobj);

    $response = new RedirectResponse(Url::fromRoute('commerce_cart.page')->toString());
    return $response;

2

You must use the commerce_cart.cart_manager service instead.

So $this->cartManager->emptyCart($cart); should do the trick.

Update: The reason why you get an error is because you try to call emptyCart on $cart then it's NULL.

You must wrap the line where you empty the cart in an if statement, like this:

if (!empty($cart)) {
  $this->cartManager->emptyCart($cart);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.