最近在 Magento 项目中有这样一种需求,在下订单时,修改该商品的 Custom Option。现列出一下解决方案:
测试时使用的 Magento 版本是 1.7.0.2。
动态修改商品的 Custom Option
$_product = $this->getProduct();
$i = 1;
foreach ($_product->getOptions() as $o) {
echo "[b]Custom Option:" . $i . "[/b]<br/>";
echo "Custom Option TYPE: " . $o->getType() . "<br/>";
echo "Custom Option TITLE: " . $o->getTitle() . "<br/>";
echo "Custom Option Values: <br/>";
// Getting Values if it has option values, case of select,dropdown,radio,multiselect
$values = $o->getValues();
foreach ($values as $v) {
//print_r($v->getData());
echo $v["title"] . " Sort Order: " . $v["sort_order"] . "<br/>";
$rand = rand(0, 100);
$v["sort_order"] = $rand;
$v->setOption($o)->save();
/* Or else, you can set multiple option value simultaneously.
$v->setTitle("morad")
->setSku("kk")
->setPriceType("fixed")
->setSortOrder(0)
->setPrice(floatval(13.0000));
$v->setOption($o)->save();
*/
}
$i++;
}
动态添加商品的 Custom Option
function setCustomOption($productId,
$title,
array $optionData,
array $values = array()) {
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
if (!$product = Mage::getModel('catalog/product')->load($productId)) {
throw new Exception('Can not find product: ' . $productId);
}
$defaultData = array(
'type' => 'field',
'is_require' => 0,
'price' => 0,
'price_type' => 'fixed',
);
$data = array_merge($defaultData,
$optionData,
array('product_id' => (int)$productId,
'title' => $title,
'values' => $values));
$product->setHasOptions(1)->save();
$option = Mage::getModel('catalog/product_option')->setData($data)
->setProduct($product)->save();
return $option;
}
使用示例:
$options = array('type' => 'radio',
'is_require' => 1,
'price' => 0,
'price_type' => 'fixed');
$values = array(
array(
'title' => '2kg',
'price' => 10,
'price_type' => 'fixed',
'sku' => 'w1',
'sort_order' => 1
),
array(
'title' => '4kg',
'price' => 20,
'price_type' => 'fixed',
'sku' => 'w2',
'sort_order' => 2
),
array(
'title' => '10kg',
'price' => 40,
'price_type' => 'fixed',
'sku' => 'w3',
'sort_order' => 3
)
);
setCustomOption(166, 'Weight', $options, $values);
FYI:
- http://www.2coding.com/mage/magento-set-custom-option-product/
- http://stackoverflow.com/questions/10798158/how-to-update-custom-options-programatically-in-magento