-->

Magento: Programatically update cart via event

2020-07-30 02:47发布

问题:

I'm hooking into the sales_quote_save_after event disaptcher. Firstly as a test I'm trying to get the items in the cart and change their prices to 0. After I do that I'll be building in some other stuff.

I'm having trouble. I can change the unit price no problem, but when I go to recalculate the cart totals the prices are reverting back to the original price.

public function sales_quote_save_before($observer) {

    if (Mage::registry('basket_observer_executed')) {
        return $this;
    }

    $quote = $observer->getEvent()->getQuote();

    foreach ($quote->getAllItems() as $item) {
        if($item->getId()) {    
            $item->setCustomPrice(0);
        }
    }

    Mage::register('basket_observer_executed', true);

    $quote->save();
    $quote->setTotalsCollectedFlag(false)->collectTotals();
}

Can anyone point me towards maintaining the new price whilst doing the recalculation of the totals?

回答1:

I'd try using a different event. I always use checkout_cart_save_after for doing similar actions.Using the event I mentioned, use the following code:

$cart = $observer->getData('cart');

$quote = $cart->getData('quote');

$items = $quote->getAllVisibleItems();

foreach($items as $item)
{
    $item->setCustomPrice(0);
    $item->setOriginalCustomPrice(0);
    $item->getProduct()->setIsSuperMode(true);
    $item->save();
}
$quote->save();
$quote->setTotalsCollectedFlag(false)->collectTotals();