我想以编程方式创建具有多个自定义选项的产品。我当前的代码是贝娄,但只保存了最后一个选项。有人可以帮忙吗?
$options = array(
array(
'is_delete' => 0,
'title' => 'First Line',
'type' => 'text',
'is_require' => 0,
'sort_order' => 1,
),
array(
'is_delete' => 0,
'title' => 'Second Line',
'type' => 'text',
'is_require' => 0,
'sort_order' => 2,
)
);
$product = Mage::getModel('catalog/product')->load($id);
$optionInstance = $product->getOptionInstance();
foreach($options as $option){
$product->setHasOptions(1);
if (isset($option['is_require']) && ($option['is_require'] == 1)) {
$product->setRequiredOptions(1);
}
$optionInstance->addOption($option);
$optionInstance->setProduct($product);
$product->save();
}
答案 0 :(得分:3)
好的,我的解决方案如下:
$options = array(
array(
'title' => 'First Line',
'type' => 'field',
'is_require' => 0,
'sort_order' => 1,
),
array(
'title' => 'Second Line',
'type' => 'field',
'is_require' => 0,
'sort_order' => 2,
)
);
$product = Mage::getModel('catalog/product')->load($id);
$product->setHasOptions(true)->save();
foreach($options as $option_data){
$option = Mage::getModel('catalog/product_option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($option_data);
$value = Mage::getModel('catalog/product_option_value');
$value->setOption($option);
$option->addValue($value);
$option->save();
$product->addOption($option);
$product->save();
}
答案 1 :(得分:2)
这里的代码如下:
$selectOptionId = 1379;
$selectOptionValueId = 794;
$textOptionId = 1380;
$fileOptionId = 1381;
// Update custom option of Text Field type
$customTextFieldOption = array(
"title" => "Custom Text Field Option Title Updated",
"type" => "field",
"is_require" => 1,
"sort_order" => 20,
"additional_fields" => array(
array(
"price" => 13.00,
"price_type" => "fixed",
"sku" => "custom_text_option_sku_updated",
"max_characters" => 127
)
)
);
Mage::getModel('catalog/product_option_api')->update($textOptionId, $customTextFieldOption, $store = null);
//更新Dropdown类型的自定义选项
$customDropdownOption = array(
"title" => "Custom Dropdown Option Title Updated to Multiselect",
"type" => "multiple",
"additional_fields" => array(
array(
"value_id" => $selectOptionValueId,
"price" => 14.00,
"price_type" => 'percent',
"sku" => "custom_select_option_sku_1 updated",
"sort_order" => 26
)
)
);
Mage::getModel('catalog/product_option_api')->update($selectOptionId, $customDropdownOption, $store = null);
如果它不起作用,让我说吧
答案 2 :(得分:0)
在以下示例代码中,我添加标题为“大小”的自定义选项,并为其添加了两个值“长”和“短强>”。
$productId = YOUR_PRODUCT_ID;
$product = Mage::getModel('catalog/product')->load($productId);
$options = array(
'title' => 'Size',
'type' => 'drop_down',
'is_required' => 1,
'sort_order' => 0,
'values' => array(
array(
'title' => 'Long',
'price' => 10.50,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 0,
),
array(
'title' => 'Short',
'price' => 0,
'price_type' => 'percent',
'sku' => 'test-product-sku',
'sort_order' => 0,
)
)
);
$product->setProductOptions(array($options));
$product->setCanSaveCustomOptions(true);
$product->save();