3

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.

1
  • you can use this Event catalog_product_prepare_save
    – Keyul Shah
    Nov 27, 2014 at 12:02

1 Answer 1

5

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.

4
  • 1
    Can't you do if ($newProduct->getData('price') != $newProduct->getOrigData('price')) OrigData should hold the data that was in the field when the object was first loaded.
    – Richard
    Nov 27, 2014 at 13:31
  • 1
    Actually yes I think you are quite right - forgot about the original data array. Nov 27, 2014 at 13:34
  • Why in this case the <events> tags are between the <adminhtml> tags?
    – VDarricau
    Feb 8, 2016 at 14:17
  • 3
    Because you want the event observer to apply for admin only, i.e. not the frontend. Feb 8, 2016 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.