4

I'm encountering the problem of the url key being unset and the visibility not retaining its original value when I'm retrieving a product collection, iterating through it to set a value per product, and then saving it as in the following:

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToFilter('type_id', 'configurable');

foreach ($products as $product) {
    $product->setDescription('custom description');
    $product->save();
}

However, if I add those attributes to be selected

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('url_key')
    ->addAttributeToSelect('visibility')
    ->addAttributeToFilter('type_id', 'configurable');

Then I'm able to save the product fine, and the url key and visibility retain their values.

A. Is this the correct way to handle this, or is there something else that I am supposed to set before I retrieve the collection?

B. Are there any other product attributes that have this same issue? (I didn't notice any other ones)

Thanks.

1
  • 2
    afaik this is a known bug in magento. Which version do you use? Mar 12, 2014 at 19:53

1 Answer 1

2

Don't save a product from a collection.
A product collection item does not contain all the data for a product. You can end up losing a lot of attribute values if the attribute is not in the collection.
If you want to call $product->save() to update a product, just to be on the safe side, first you must call $product->load().

If you want to update just one attribute (or a few of them) use this. It's faster.

Mage::getModel('catalog/product_action')->updateAttributes(
    array($productId),
    array('attribute_code'=>$attributeValue),
    $storeId //use '0' for default values
);

The code above works for many products at a time, and many attributes at a time.

4
  • No this shouldn't be the case (at least I think so), because the attributes should be checked against $_origData and the object is aware of its $_partialLoaded status. Mar 12, 2014 at 21:00
  • @FabianBlechschmidt. Not sure, but you may be right. Either way...you shouldn't update products using ->save(). It's faster using Mage::getModel('catalog/product_action')->updateAttributes()
    – Marius
    Mar 12, 2014 at 21:02
  • I forget this method all the time, thanks for remembering. Mar 12, 2014 at 21:05
  • Mage::getModel('catalog/product_action')->updateAttributes() may cause some other problems because related events not fire.
    – ndlinh
    May 13, 2019 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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