使用自定义选项以编程方式添加到购物车时出错

时间:2016-03-29 04:35:57

标签: magento magento-1.9

我正在尝试将客户(以编程方式)添加到购物车但收到错误"无效请求添加产品以引用"。我有简单的产品(带有自定义选项)和可配置的产品。以下是我的代码。请帮忙。非常感谢提前。

public function addtocartAction(){
try {
    $cusId = $this->getRequest()->getParam('cusId');
    $customer = Mage::getModel('customer/customer')->load($cusId);
    $quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
    $quoteId = $quote->getId();
    //$products = $this->getRequest()->getParam('products');
    $products = json_decode('[{"proId": "906","proQty": "1", "options":{"17":"wq","16":"18"}}]');

    foreach($products as $product) {
        /*if (!$product->getId()) {
            throw new Exception();
        }*/
        foreach ($product->options as $optKey => $optValue) {
            $optAll[$optKey] = $optValue;
        }

        $mainProduct = Mage::getModel('catalog/product')->load($product->proId);
        $params = array(
            'product' => $product->proId,
            'qty'     => $product->proQty,
            'options' => $optAll
        );
        echo "<pre />"; print_r($params);
        $quote->addProduct($mainProduct, $params);
        $quote->setIsActive(1);
        $quote->collectTotals()->save();
    }
    $rslt['success'] = '1';
    $rslt['message'] = 'Product has been succefully added to cart';
}
catch(Exception $e){
    $rslt['success'] = '0';
    $rslt['message'] = $e->getMessage();
}
print_r(json_encode($rslt));

}

1 个答案:

答案 0 :(得分:1)

尝试使用购物车代替引用。 这对我有用:

$cart = Mage::getModel('checkout/cart');
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
        'product' => $product->proId,
        'qty'     => $product->proQty,
        'options' => $optAll
);
$cart->init();
$cart->addProduct($mainProduct, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);