Magento – Magento observer is not viewing product details

event-observermagento-1.8PHP

I have created custom checkout_cart_save_before observer in magento by create the following files

app/etc/modules/Cart_Override.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Cart_Override>
            <codePool>local</codePool>
            <active>true</active>
            <depends>
                <Mage_Contacts />
            </depends>
        </Cart_Override>
    </modules>
</config>

app/code/local/Cart/Override/etc/config.xml

<?xml version="1.0"?>
<config>
    <global>
        <models>
            <cartoverride>
                <class>Cart_Override_Model</class>
            </cartoverride>
        </models>
        <events>
            <checkout_cart_save_before>
                <observers>
                    <cart_override_qty_observer>
                        <type>singleton</type>
                        <class>Cart_Override_Model_Qtyc_Observer</class>
                        <method>checkout_cart_save_before</method>
                    </cart_override_qty_observer>
                </observers>
            </checkout_cart_save_before>     
        </events>
    </global>
</config>

and app/code/local/Cart/Override/Model/Qtyc/Observer.php

class Cart_Override_Model_Qtyc_Observer extends Varien_Event_Observer
{

    public function checkout_cart_save_before($observer)
    {
        $action  = Mage::app()->getFrontController()->getAction();
        $product = $observer->getProduct();
        echo "<pre>";
        print_r($product);
        echo "</pre>";
        die();
    }

}

The observer is working fine, when i click the add to cart button it is going to checkout_cart_save_before function. But i could not get the product values from the observer using the following code inside the checkout_cart_save_before function

$product = $observer->getProduct();

I have to add something for get the product details from the observer parameter?….any guess??

Best Answer

The event itself does not have the products directly. See where it is being called:

Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

You only have the cart object as a parameter to the event. You can get the items from the cart and find the product from each item.

$items = $observer->getEvent()->getCart()->getItems()

Will give you the cart items collection.

And then you would need to run this:

foreach($items as $item) {
    $product = $item->getProduct();
    //here you do what you want with the product.
}
Related Topic