Magento – Fix catalog_product_save_before Event Not Firing on $product->save()

event-observerproduct-attributeproducts

I need to create a custom attribute for products, which value is updated on product save, based on other attribute's value.

So creating an observer for event catalog_product_save_before works fine when saving products manually.

Unfortunately this event doesn't fire when I loop through 100s of products in my shop with:

set_time_limit(0);
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $product) {
    $product->save();
}

My test observer function:

public function updateProductDetails($observer) {
   Mage::log('inside the observer');
}

I need either new event that will fire on $product->save() or new method of saving all my products at once, that will fire this event catalog_product_save_before.

I would appreciate your suggestions.

Best Answer

As explained in the comments...
You should never call ->save to update something without calling load before it. calling save from an object inside a collection may lead to loss of data.

If you want to bulk update products you can do this. It's faster and safer.

$productIds = an array with product ids to update
$values = array('attr_code_one' => 'value 1', 'attr_code_two' => 'value 2', ....);
$storeId = 0; //store id for which you need the changes. 0 means default values.
Mage::getSingleton('catalog/product_action')->updateAttributes(
    $productIds,
    $values,
    $storeId
);