我必须创建一个(虚拟的,简单的)产品,然后以编程方式添加到购物车,到目前为止我已经这样做了。现在我必须在此产品添加到购物车时设置自定义选项。但没有任何反应。这是我的代码
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
'product' => $product->getId(), // This would be $product->getId()
'qty' => 1,
'options' => array(
34 => "value",
35 => "other value",
53 => "some other value"
)
);
try {
$cart->addProduct($product, new Varien_Object($params));
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$cart->save();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
答案 0 :(得分:6)
以下是我获得成功的代码。
$a_options = array(
'options' => array(
'label' => 'Choice',
'value' => $pkg_selected_products,
)
);
$quoteItem->addOption(new Varien_Object(
array(
'product' => $quoteItem->getProduct(),
'code' => 'additional_options',
'value' => serialize($a_options)
)
));
$quote->addItem($quoteItem);
$quote->save();
答案 1 :(得分:0)
我遇到了日期自定义选项字段的问题,因为我的控制器功能添加了产品。
所以我必须以Magento方式打破/爆炸,并将其放在AddProduct()
的参数上,如下所示。
try {
$cart = Mage::getModel('checkout/cart');
$previousItemCount = $cart->getQuote()->getItemsCount();
if ($previousItemCount <= 0) {
$cart->init();
}
$params = $this->getRequest()->getParams();
$product = Mage::getModel('catalog/product')->load($params['product_id']);
$date = explode('/', $params['product_dtinvoice']);
$date = array(
'month' => $date[0],
'day' => $date[1],
'year' => $date[2],
);
$cart->addProduct(
$product,
new Varien_Object(array(
'product' => $product->getId(),
'qty' => 1,
'options' => array(
'4' => array(
'month' => $date['month'],
'day' => $date['day'],
'year' => $date['year']
),
'2' => $params['product_ean'],
'3' => $params['product_serialnumber'],
'1' => $params['product_seller'],
),
))
);
$cart->save();
if ($previousItemCount < $cart->getQuote()->getItemsCount()) {
$return = array('result' => true, 'msg' => '');
} else {
$return = array('result' => false, 'msg' => 'Did not possible to add this product to cart. Please contact the administrator');
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($return));
} catch(Exception $e) {
Mage::throwException($e->getMessage());
}