Cart – How to Replace Items Programmatically

cartevent-observerquote

I tried two different approaches for this, but both failing at different point.

  1. By calling $cart->truncate()->save() and then $cart->addProduct($product, $qty). But instead of replacing the whole cart with new items, overlapping items (with or without the same quantity) will be deleted anyways.
  2. I also tried $quote->removeAllItems()->collectTotals()->save() and then $cart->addProduct($product, $qty), but when the quantity of an overlapping item is collectively larger than stock level, it will prompt a false out of stock error message.

More on 2

I have dived into the code which checks stock level, which is Mage_CatalogInventory_Model_Observer::checkQuoteItemQty().

Every time I test with code in 2), a total of four times it checked and in the 3rd time the $qtyForCheck of that particular overlapping item is summed up with quantities before AND after removeAllItems(), effectively generating a false error prompt.

Best Answer

Why not re-declare cart & start over like this?

$session = Mage::getSingleton('checkout/session');
$session->getQuote()->delete();
$session->clear();

$cart = Mage::getModel('checkout/cart');
$cart->setQuote($session->getQuote());

$product = Mage::getModel('catalog/product') -> load($product_id);
if ($product) {
    if ($product -> isSaleable()) {
        $cart -> addProduct($product, array('qty' => $qty));
    }
}

// $session->setCartWasUpdated(true); // Not really necessary - Vicary
$cart->save();