Magento – Url key disappearing and visibility changing when saving a product from collection

product

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.

Best Answer

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.