Search code examples
sqlmagentoinstallationentity-attribute-value

How to update the values of Magento products using installer/update scripts and Magento abstractions?


I added a custom eav attribute to my Magento application product entity using an installer script (Basically, following the procedure described here: Installing Custom Attributes with Your Module). Now, I want to use an update script to change (populate) the values of this attribute for each product according to some criteria (based on the product category). The script I attempted to use was essentially like this:

$attributeValues = array(...) // Map from $productId to the desired  $value
$product = Mage::getModel('catalog/product');
foreach($attributeValues as $productId=>$value){
    $product->load($productId)->setMyAttribute($value);
    $product->save();
}

My questions would then be: Is it ok to use this level of abstraction (Mage::getModel('catalog/product') and its methods) in update scripts? If it isn't, how would you recommend to change these attribute values using update scripts (without requiring sql)?

The script I used (until now) has not worked and failed with the error:

Call to a member function getStoreIds() on a non-object

in a magento core file.

I don't know if this error is a Magento bug or is a problem with how I'm using the update scripts.

I'm using Magento 1.4.0.1


Solution

  • Try adding Mage::app()->setUpdateMode(false) in your sql upgrade script. e.g.

    $installer = new Mage_Eav_Model_Entity_Setup('core_setup');;
    $installer->startSetup();
    Mage::app()->setUpdateMode(false);
    Mage::app()->setCurrentStore('your_store_code_here');
    

    If you look in Mage::app()->getStore() you will see the following snippet that returns an incorrect store which is required for saving a product.

    if (!Mage::isInstalled() || $this->getUpdateMode()) {
            return $this->_getDefaultStore();
        }