7

This has been asked many times before but with no working answer.

I have multiple stores and some attributes have been overridden. I want to change these attributes to 'use default value' with a script.

Here is an image showing store views and 'use default value' checkboxes http://dl.dropbox.com/u/3209649/storeviews-and-defaultvalues.png (not allowed to post images yet)

In app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php setData() is used with false for the second argument when 'Use Default Value' has been selected for any attributes.

/**
 * Check "Use Default Value" checkboxes values
 */
if ($useDefaults = $this->getRequest()->getPost('use_default')) {
    foreach ($useDefaults as $attributeCode) {
        $product->setData($attributeCode, false);
    }
}

The following code attempts to set the 'name' attribute to 'use default values' for product 1 in store 3 using the same method.

require_once '../app/Mage.php';
Mage::app(3);

$product = Mage::getModel('catalog/product')->load(1);

$product->setData('name', false); # as used in ProductController.php
$product->save();

Using

$product->setData('name', 'anything');

correctly sets the 'name' attribute to 'anything' but false does not set it to 'use default value'

'Use Default Value' is not stored anywhere in the database so within the controller for the admin interface there must be another procedure that deletes the attribute row?

Related Links here -> http://pastebin.com/raw.php?i=j7fwu9H6 (not allowed to post links yet either)

Jacob Dorman
  • 341
  • 1
  • 4
  • 16

1 Answers1

14

This doesn't work because you need the current store being the admin store for this kind of operation.

To make a specific store view use the default value for a given attribute:

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$product = Mage::getModel('catalog/product')
    ->load($product_id)         // in your case: 1
    ->setStoreId($store_id)     // in your case: 3
    ->setData($attr, false)     // in your case: 'name'
    ->save();
Jürgen Thelen
  • 12,745
  • 7
  • 52
  • 71
  • 1
    I'm not sure I understand why it works that way but I can confirm it does. I've been looking for a solution to this for a long time. Thankyou. – Jacob Dorman Apr 25 '12 at 14:32
  • Hi, I faced a problem when I runned a script without giving the currentStore, it broke my back office, changing default values with custom values on the products. In my script I just updated the products weight but it created custom values like custom price or custom visibility randomly for the products. I deleted it in db afterward, but I don't get why it is important to call the setCurrentStore function... Could you explain a little more ? – beluga Jul 12 '13 at 13:33
  • `Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);` After many hours of looking over perfect code, my only problem was that I needed this. – FactoryAidan Jun 20 '16 at 21:51