我目前正在Magento 1.9上开发一个管理模块Cart
我想把一个产品添加到购物车(我尝试了很多不同的方法),这就是为什么我请求你的帮助。
我的模块扩展了magento的其余API,我已经管理了我的购物车(产品数量)的更新,但现在我希望通过POST方法添加一个新产品。我当然是客户了。我为这个角色定义了创建权限。(我可以做更新没有问题)
下面是我的代码:protected function _create(array $data){
$store = $this->_getStore();
Mage::app()->setCurrentStore($store->getId());
$cart = Mage::getModel('checkout/cart');
$cart->init();
$productCollection = Mage::getModel('catalog/product')->load(4);
// Add product to cart
$cart->addProduct($productCollection,
array(
'product_id' => $productCollection->getId(),
'qty' => '1'
)
);
// Save cart
$cart->save();
}
在这个简单的示例中,我尝试在数量1中添加产品id 4。我的问题是我在日志中没有错误,一切似乎都过去了。但是当我进入购物车时,没有产品可以添加…
返回代码200 OK
你有什么建议可以帮助我吗?谢谢你的帮助
对
我终于找到了解决办法;)
事实上,当您想在结账前到达购物车时,magento使用定义"Quote"…对于Magento....的初学者来说不容易理解所以为了方便研究那些像我一样有麻烦的人,这里是我在购物车中添加新产品的代码(在结帐之前):
//$data['entity_id'] = The id of the product you want to add to the cart
//$data['qty'] = The quantity you want to specify
protected function _create(array $data)
{
$store = $this->_getStore();
Mage::app()->setCurrentStore($store->getId());
// Get Customer's ID
$customerID = $this->getApiUser()->getUserId();
// Load quote by Customer
$quote = Mage::getModel('sales/quote')
->loadByCustomer($customerID);
$product = Mage::getModel('catalog/product')
// set the current store ID
->setStoreId(Mage::app()->getStore()->getId())
// load the product object
->load($data['entity_id']);
// Add Product to Quote
$quote->addProduct($product,$data['qty']);
try {
// Calculate the new Cart total and Save Quote
$quote->collectTotals()->save();
} catch (Mage_Core_Exception $e) {
$this->_error($e->getMessage(),Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
}
}
我希望这能帮助到别人
对
Carniflex