3
votes

I want to change some values of some products while adding them to the cart in Magento CE 1.7

Im trying with the Observer checkout_cart_add_product_complete for this. Change the price (CustomPrice) works well if I try to change the product name or product images, its not saved.

Is there a way to change this attributes already on adding to cart?

public function checkout_cart_add_product_complete(Varien_Event_Observer $observer) {
    [...]
            // Set new Price
            $lastAddedItem->setOriginalCustomPrice($originalProduct->getPrice());
            $lastAddedItem->setCustomPrice($originalProduct->getPrice());

            // Set Product-Name
            $lastAddedItem->setName($originalProduct->getName());

            // Set Product-Images
            $lastAddedItem->setImage($originalProduct->getImage());
            $lastAddedItem->setSmallImage($originalProduct->getSmallImage());
            $lastAddedItem->setThumbnail($originalProduct->getThumbnail());

            // Save updated Item and Cart
            //$lastAddedItem->save();
            Mage::getSingleton('checkout/cart')->save();

            // Recalc Totals and save
            $quote->setTotalsCollectedFlag(false);
            $quote->collectTotals();
            $quote->save();

            Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
1

1 Answers

9
votes

The function Mage_Sales_Model_Quote_Item::setProduct resets some of the basic information each time a product is saved (updated). Luckily there is an event "sales_quote_item_set_product" you can latch onto.

config.xml

<config>
...
    <global>
        <events>
            <sales_quote_item_set_product>
                <observers>
                    <samples>
                        <type>singleton</type>
                        <class>samples/observer</class>
                        <method>salesQuoteItemSetProduct</method>
                    </samples>
                </observers>
            </sales_quote_item_set_product>
        </events>
    <global>
...
</config>

Observer.php

class Mynamespace_Samples_Model_Observer
{
    public function salesQuoteItemSetProduct(Varien_Event_Observer $observer)
    {
        /* @var $item Mage_Sales_Model_Quote_Item */
        $item = $observer->getQuoteItem();

        $item->setName('Ians custom product name');

        return $this;
    }
}