以编程方式将产品添加到购物车不会更新总计

时间:2016-07-11 09:10:38

标签: php magento

我想从外部文件

添加产品到购物车

这是我的代码

require_once 'app/Mage.php';
Mage::app();

$session = Mage::getSingleton('customer/session');

Mage::getSingleton('checkout/cart')->getQuote();

$productId = 123;
$productQuantity = 1;
$productModel = Mage::getSingleton('catalog/product');
$productObj = $productModel->load($productId);

if (!$quoteObj) {
    $quoteObj = new Mage_Sales_Model_Quote();
}

$store_id = 1;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);

$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($productQuantity);
$quoteItem->setStoreId($store_id);

$quoteObj->addItem($quoteItem);
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->setCustomerId(null);
$quoteObj->save();
$quoteId = $quoteObj->entity_id;

$quote1 = Mage::getModel('sales/quote')->setStoreId($store_id)->load($quoteId);
print_r($quote1->getData());

印刷信息。

    [grand_total] => 0
    [base_grand_total] => 0
    [subtotal] => 0
    [base_subtotal] => 0
    [subtotal_with_discount] => 0
    [base_subtotal_with_discount] => 0

这里我发现它并没有更新总数。

为什么我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您正在保存报价,但我不确定这是否足够。你应该尝试保存购物车。在打印collectTotals之前尝试getData

$cart = Mage::getSingleton('checkout/cart');
$quote = $cart->getQuote();

Your code .... 

$cart->save();

$quote = Mage::getModel('sales/quote')->setStoreId($store_id)->load($quoteId);
$quote->setTotalsCollectedFlag(false)->collectTotals();
print_r($quote->getData());