Leon Lai
Leon Lai

Reputation: 33

how to update cart total after change item price with observer?

I want to add some free gift to cart , so I create an observer, the code is:

<?php
 class Free_Checkout_Model_Observer
{
    public function modifyPrice(Varien_Event_Observer $observer)
    {
        $event = $observer->getEvent();
        $quote = Mage::getModel('checkout/session')->getQuote();
        $quote_item = $event->getQuoteItem();
        $productId  = $event->getQuoteItem()->getProduct()->getId();

        $product        = Mage::getModel('catalog/product')->load($productId);
        $productData    = $product->getData();

        if($productData['gift']){
            $new_price = 0;
            $quote_item->setOriginalCustomPrice($new_price);
            $quote_item->setCustomPrice($new_price);
            $quote_item->save();
        }

    }


}

but when I add an item to cart , in the shopping cart, the subtotal is 0, is anyone tell me how to solve this issue? when I add one more item or refresh the shopping cart page, the subtotal is correct

Upvotes: 1

Views: 10778

Answers (2)

Amit Kumar
Amit Kumar

Reputation: 1772

Try this one

$quote = Mage::getSingleton('checkout/session')->getQuote();
foreach($quote->getAllItems() as $quote_item) {
    $product = Mage::getModel('catalog/product')->load($quote_item->getProductId());
    $productData  = $product->getData();
    if($productData['gift']){
        $new_price = 0;
        $quote_item->setOriginalCustomPrice($new_price);
        $quote_item->setCustomPrice($new_price);
        $quote_item->getProduct()->setIsSuperMode(true);
    }
}
$quote->save();

Upvotes: 1

TaganPablo
TaganPablo

Reputation: 359

Try

$quote->collectTotals()->save()

at the end of your function

Upvotes: 3

Related Questions