Programatically clear the cart of a logged-in user
-
13-04-2021 - |
Вопрос
TL;DR When a customer is logged in, Mage::getSingleton('checkout/session')->clear(); doesn't clear their cart. I need something that will.
I've asked this as part of another question, but i discovered it was actually two problems, other other one now fixed.
I'm programatically creating an order in a controller using the items in the cart. After the order is saved the cart should be cleared. I do this using
Mage::getSingleton('checkout/session')->clear();
which works fine most of the time. The problem comes when the customer is logged-in. If they are logged in the cart doesn't clear. I've found other solutions (like load the cart items and removed them one at a time in a loop) but they don't meet all my requirements. WHat I need is something that will:
- remove all the items (obviously)
- stay on the same page (why loading the cart doesn't seem to work. I end up redirected to the cart page)
- NOT go to another page and then come back (2 redirects won't work in this case)
Is there something different I need to do when they are logged in? How can I get the cart cleared? Thanks all for the help.
Решение
Check quote status is_active for the quote (sales_flat_quote) regarding to the created order. If its active (value is 1) set it inactive ($quote->setIsActive(0)->save()
) after successfully order creation and than clear checkout session.
Другие советы
This is against standard Magento logic, so you need a custom module that will observe customer_logout event and execute the following code bit:
foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ){
Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();
}
/** @var Mage_Sales_Model_Quote $quote */
$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->removeAllItems()->save();
This should do a job (note that without checking if cart actually has items it will not work good):
$cart = Mage::getSingleton('checkout/cart');
if (count($cart->getItems())) {
$cart->truncate();
$cart->save();
}
If you want to clear cart of a specific customer, here is the way
$customerId = 4;
$quote = Mage::getModel('sales/quote')->loadByCustomer($customerId);
$quote->removeAllItems()->save();