[原创] Magento 动态添加或修改商品的 Custom Option

  最近在 Magento 项目中有这样一种需求,在下订单时,修改该商品的 Custom Option。现列出一下解决方案:

  测试时使用的 Magento 版本是 1.7.0.2。

[b]动态修改商品的 Custom Option[/b]
$_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++;
}

[b]动态添加商品的 Custom Option[/b]
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;
}

[b]使用示例:[/b]
$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:
[list]
[*][url]http://www.2coding.com/mage/magento-set-custom-option-product/[/url]
[*][url]http://stackoverflow.com/questions/10798158/how-to-update-custom-options-programatically-in-magento[/url]
[/list]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值