Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento: Programatically update cart via event

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?

like image 805
iamjonesy Avatar asked Nov 20 '25 01:11

iamjonesy


1 Answers

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();
like image 90
Ash Smith Avatar answered Nov 21 '25 15:11

Ash Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!