user1745154
user1745154

Reputation: 41

Magento : catalog_product_save_before with mass action

I've made a new mass action to refresh some attributes on selected products based on a algorithm.

I need to trigger "catalog_product_save_before" as if I was saving my product trough the standard admin product creation/edition.

Thanks a lot for your help.

Code sample :

<catalog_product_save_before>
    <observers>
        <SaponeWebConcept_AttributeToCategories>
            <type>singleton</type>
            <class>attributetocategories/observer</class>
            <method>beforeSave</method>
        </SaponeWebConcept_AttributeToCategories>
    </observers>
</catalog_product_save_before>

Where it works (standard product creation/edition)

$event = $observer->getEvent();
$product = $event->getProduct();
//And then I edit my product

Where it doesn't : I get my $productID, load it, then save, but the above code isn't triggered.

$product = Mage::getModel('catalog/product')->load($productID);
//Some verifications
$product->save();

$productID is set in a foreach where I got all selected products ID of the product grid.

Upvotes: 1

Views: 5425

Answers (3)

Tam&#225;s Szab&#243;
Tam&#225;s Szab&#243;

Reputation: 41

You need to call the setDataChanges() method on the product object to indicate something was/will be changed.

Here is a simple example from my code:

Mage::getModel('catalog/product')->load($productId)->setDataChanges(true)->save();

This looks a bit odd on its own, but I have an observer, which will do some magic on product save.

If you have a look at Mage_Core_Model_Abstract::save() you can see it checks if the product needs to be saved:

if (!$this->_hasModelChanged()) {
    return $this;
}

Therefore if you don't make any changes to the product or don't tell it that there are data changes, then it assumes there is nothing to save and the catalog_product_save_before won't be triggered.

Upvotes: 0

Sergey Croitor
Sergey Croitor

Reputation: 21

Mass action doesn't fire catalog_product_save_before event. use catalog_product_attribute_update_before event instead and then do nested product load/save

I just did it in my magento 1.6.2 code and it worked fine. loop through product ids{ $product = Mage::getModel('catalog/product')->load($productID); ... some code ... $product->save(); }

be sure to set all important changes to a product before nested $product->save() invocation so that this event handler has all product attributes in correct state

Upvotes: 2

Michael Leiss
Michael Leiss

Reputation: 5670

I haven't looked it up in code, but I'm guessing your mass action is not firing a save at all. As far as I can remember a mass action save jumps into the same save model method as the regular save does.

Upvotes: 0

Related Questions