我正在尝试在购物车中添加产品,但购物车保持空白.这是我的代码
try{
$product_model = Mage::getSingleton('catalog/product');
// Load product
$_sku = "1-574#AD-B00731";
$my_product_id = $product_model->getIdBySku($_sku);
$my_product = $product_model->load($my_product_id);
$qty_value = 1;
// Add to cart
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($my_product, array('qty' => $qty_value));
$cart->save();
print_r($cart->getItemsQty().PHP_EOL);
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
var_dump("working");
}
catch(Exception $e){
return $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
当我打印$cart->getItemsQty()我的物品数量增加但我的购物车仍然是空的.我认为这Mage::getSingleton('checkout/session')->setCartWasUpdated(true);是不正常的.
有人知道什么不起作用吗?
编辑1:我使用Magento 1.8.0,因此通过url查询因form_key而无效
尝试改变
$cart = Mage::getModel('checkout/cart');
Run Code Online (Sandbox Code Playgroud)
到
$cart = Mage::getSingleton('checkout/cart');
Run Code Online (Sandbox Code Playgroud)
Cart 是一个单例,因为您的商店中只有 1 个用户可以使用 1 个购物车,并且所有想要使用它的人都可以将其称为 getSingleton,而无需创建新对象。如果您使用 Mage::getModel('checkout/cart') 它将创建一个新对象。是的,它允许您将报价保存到数据库,但这不是当前活跃的客户购物车。
| 归档时间: |
|
| 查看次数: |
9718 次 |
| 最近记录: |