Question

I've noticed in a couple community extensions we have installed that they observe the event catalog_product_save_after, and in the triggered method they will get the product and do something to it (add additional custom attribute data or whatever) and then save it.

config.xml

<events>
    <catalog_product_save_after>
        <observers>
            <foo_bar>
                <type>singleton</type>
                <class>foo_bar/observer</class>
                <method>saveProductData</method>
            </foo_bar>
        </observers>
    </catalog_product_save_after>
</events>

Observer.php

public function saveProductData(Varien_Event_Observer $observer)
{
    $product = $observer->getEvent()->getProduct();
    try {
        $blocks = $this->_getRequest()->getPost('content_blocks');
        $product->setData('content_blocks', $content_blocks_value);
        $product->save();
    } catch(Exception $e) {
        Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
    }
}

This seems like it would cause some kind of infinite product save event triggering.. although it doesn't seem to be the case; using a debug/log statement I can see when saving a product it gets saved several times but not infinitely.

My question is, is this bad practice, and should these extensions not have passed Magento's extension marketplace Quality Assurance? If it is, what would be the proper way to implement?

Était-ce utile?

La solution

This is no bad practice :)

The problem is this piece of code $product->save();.

The observer method is correct, but with this line catalog_product_save_after is triggered again, and again ... resulting in an infinite loop :)

Just as a note ... if you want to set data to the product catalog_product_save_before could fit better.


Edit: if you want to set an attribute value on save action, i'd use catalog_product_save_before:

public function saveProductData(Varien_Event_Observer $observer)
{
    $product = $observer->getProduct();
    $value = /* your code here */
    $product->setData('your_attribute_code', $value);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange
scroll top