Magento – Using Event Observer to Change Prices

adminhtmlcatalogevent-observerprice

I looking for a Event to be triggered when a user, via adminhtml or API/SOAP, change prices of a product.

I have been check this, unsuccessfully: https://www.nicksays.co.uk/magento-events-cheat-sheet-1-7/

If the event you are looking for does not exist, think about doing overridden the core, at the time the product is safe. What do you think of this idea?

Any idea is welcome, thank you.

Best Answer

Using an observer is always your best choice, but there won't always be an observer for everything you want to do. In this case however you can use the event catalog_product_save_before. So in your config.xml:

<?xml version="1.0"?>
<config>
    ...
    <adminhtml>
        ...
        <events>
            ...
            <catalog_product_save_before>
                <observers>
                    <some_unique_handle>
                        <class>module/someModel</class>
                        <method>yourMethod</method>
                    </some_unique_handle>
                </observers>
            </catalog_product_save_before>
            ...
        </events>
        ...
    </adminhtml>
    ...
</config>

As the product changes have not yet been committed you can load the product in your observer (which will pull the old unmodified price data from the database) and compare against the product object passed to the observer (which will contain the price change):

<?php
class Namespace_Module_Model_SomeModel
{
    public function adminhtmlCatalogProductSaveAfter($observer)
    {
        $newproduct = $observer->getProduct();
        $oldproduct = Mage::getModel('catalog/product')->load($newproduct->getId());

        if ($oldproduct->getData('price') != $newproduct->getData('price')):
            // price has changed - do something here
        endif;
    }
}

Note the use of getData() rather than the standard magic method as class Mage_Catalog_Model_Product defines a getPrice() method which returns a calculated price for the product. Here we want the raw data from the object for comparison.

Related Topic