srgb
srgb

Reputation: 5193

Set store specific product attribute programmatically

This code:

  Mage::getModel('catalog/product')
    ->setStoreId(3)
    ->load(200445)
    ->setName("FooBar")
    ->save(); 

Yields exception:

Product with the 'foo-bar' url_key attribute already exists.

Product 200445 is assigned to the website which hosts StoreID 3. I am emulating Admin store. Magento Enterprise 1.13.1.

Upvotes: 3

Views: 2194

Answers (2)

Marius
Marius

Reputation: 15216

Try this. Is faster than loading a product and saving it:

Mage::getSingleton('catalog/product_action')->updateAttributes(
    array(200445),  //array with product ids here
    array('name'=>'FooBar'), //array with attributes to update
    3 //store id.
);

Upvotes: 3

Axel
Axel

Reputation: 10772

The url-key attribute is automatically derived from the name attribute you set. My guess is that the URL key is checked somewhere in the product save controller action, and is appended with a unique number if the URL key already exists.

You can easily do the same with your code by defining a unique URL key by using setUrlKey('foo-bar-1'), where foo-bar-1 is a unique url key.

So your code would be:

Mage::getModel('catalog/product')
->setStoreId(3)
->load(200445)
->setName("FooBar")
->setUrlKey('foo-bar-1')  //Make sure this is always unique.
->save();

If you want to loop through products and make sure each url key you set is unique, check out some solutions here which covers that topic: https://magento.stackexchange.com/a/7444/593

Upvotes: 2

Related Questions