2012-11-09 43 views
1

我想在所有產品中顯示新的選擇屬性選項。Magento爲具有升級腳本的產品添加新的選擇值/選項

我的產品每個都使用名爲「bracket_size」的選擇框屬性。該屬性有三個選項:

bracket size options

(/管理/ catalog_product_attribute /編輯/)

大部分產品只有這些選項的兩個選擇的:

product attribute config

(/admin/catalog_product/edit /)

如果我在該屏幕中選擇「18mm」,它會顯示在前端。

我想創建一個升級腳本,它將設置所有產品顯示「18mm」選項。

我已經通過選擇所有產品,獲取他們和更新他們的屬性值,這樣做:

$options = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'bracket_size')->getSource()->getAllOptions(false); 
$option18mmId = $options[0]['value']; 

foreach (Mage::getModel('catalog/product')->getCollection() as $product) { 
    // Get a writable product 
    $product = Mage::getModel('catalog/product')->load($product->getId()); 

    // All products in these attribute sets should have bracket sizes 
    $bracketSizeValue = $product->getBracketSize(); // string containing option IDs - something like '645,345' 

    if (isset($bracketSizeValue)) { 
     // Get options currently selected for this product 
     $optionIds = explode(',', $bracketSizeValue); 

     // Check if the option is already included in this product 
     if (!in_array($option18mmId, $optionIds)) { 
      // If not, rebuild the attribute value to add it 
      array_unshift($optionIds, $option18mmId); 

      // Add it back to the product 
      $product->setData('bracket_size', implode(',', $optionIds)); 
      $product->save(); 
     } 
    } 
} 

但是,這是行不通的。它會拋出一個錯誤:

Warning: Invalid argument supplied for foreach() in /.../public/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 1068 

at $product->save() line。

我該怎麼做?

+0

Magento的版本。 1.10.1.1順便說一下 –

+0

你的代碼絕對沒問題。 「錯誤沒有錯誤信息」是什麼意思? –

+0

這絕對沒有意義。你可以在循環之前回顯'Mage :: getModel('catalog/product') - > getCollection() - > getSize()'嗎? –

回答

1

如果你想保存的產品在安裝/更新腳本,那麼你需要禁用更新模式,並設置當前店鋪ID第一:

$app = Mage::app(); 
$app->setUpdateMode(false); 
$app->setCurrentStore($app::ADMIN_STORE_ID); 

理想的情況下,將恰好在保存之前完成並保存後,又恢復:

$app->setCurrentStore(null); 
$app->setUpdateMode(true); 

然後,你也可以優化你的代碼我刪除加載和保存每個產品,並在收集項目做。

收集與加載所需的屬性:改變

$collection = Mage::getModel('catalog/product')->getCollection(); 
$collection->addAttributeToSelect('bracket_code'); 

節省收集物品:

$collection->save();