1

I want to clear the cart before adding a new item to the cart.

I am trying to do using the event "checkout_cart_product_add_before" and by this code in the observer.

$allItems = $this->checkoutSession->getQuote()->getItemsCollection();

foreach ($allItems as $item) {
$itemId = $item->getItemId();
$this->cart->removeItem($itemId)->save();
}

My all items getting remove from the cart with the newly added item also.

Can anyone help me out with this?

Thanks

2

you can delete all item before they are adding as cart candidate. You can use following process

    $cart = $objectManager->create('\Magento\Checkout\Model\Cart');

    foreach ($cart->getQuote()->getAllItems() as $item) {
        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item->delete();
    }
    $cart->addProduct($newProduct, $request)->save();
  • Thanks, Its working fine. – Manish Soni Dec 2 '19 at 7:06

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.