在保存订单之前更新magento cart total

时间:2014-02-08 17:09:19

标签: php magento cart

在客户按“下订单”按钮后,我需要从购物车中删除一些产品。我可以使用自定义事件和观察者删除产品并更新购物车产品,但我无法更新购物车总数。 在观察者中,我尝试用以下方式更新价格:

    $granTotal = $cart->getGrandTotal() - $cart->getShippingAmount();
    $cart->setGrandTotal($GranTotal - $sum)->save();

    $baseGranTotal = $cart->getBaseGrandTotal() - $cart->getShippingAmount();
    $cart->setBaseGrandTotal($baseGranTotal - $sum)->save();

    $cart->setTotalsCollectedFlag(false)->collectTotals();
    $cart->save();

但购物车的总数不会改变。我发现总数也存储在购物车地址中,用于在Mage_Sales_Model_Quote collectTotals()函数中设置购物车总数。 这里:

$this->setSubtotal((float) $this->getSubtotal() + $address->getSubtotal());
$this->setBaseSubtotal((float) $this->getBaseSubtotal() + $address->getBaseSubtotal());

然后我尝试在调用collectTotals()之前更改地址总数,但是购物车总数仍然没有变化。

我的自定义事件在Mage_Checkout_Model_Type_Onepage saveOrder()函数的开头触发。

我的想法是如何更新购物车的总数。 我的观察者看起来像这样:

public function changeCart(){
    $cart = Mage::getSingleton('checkout/session')->getQuote();
    $data = array();
    $inquiry = array();
    $sum = 0;
    //remove out of stock items to save them in custom model
    foreach ($cart->getAllItems() as $item) {
        if($item->getProduct()->getData('is_in_stock') == 0){
            $cart->removeItem($item->getItemId())->save();
            $inquiry[] = $item->getProduct();
            $data['qty'][$item->getProduct()->getId()] = $item->getData('qty');
            $sum += $item->getProduct()->getFinalPrice();
            $dobavljivost = $item->getProduct()->getResource()->getAttributeRawValue($item->getProduct()->getId(), 'dobavljivost', Mage::app()->getStore());
            Mage::getSingleton('core/session')->setDobavljivost($dobavljivost);
        }
    }

    foreach($cart->getAllAddresses() as $a){
        $a->setGrandTotal(0);;
        $a->setBaseGrandTotal(0);
        $a->setData('subtotal', 0);
        $a->setData('base_subtotal', 0);
    }

    $granTotal = $cart->getGrandTotal() - $cart->getShippingAmount();
    $cart->setGrandTotal($GranTotal - $sum)->save();

    $baseGranTotal = $cart->getBaseGrandTotal() - $cart->getShippingAmount();
    $cart->setBaseGrandTotal($baseGranTotal - $sum)->save();

    $cart->setTotalsCollectedFlag(false)->collectTotals();
    $cart->save();
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

要重新计算购物车的总数,您可以尝试执行此操作

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

foreach ($cart->getAllAddresses() as $address)
{
   $address->unsetData('cached_items_nonnominal');
   $address->unsetData('cached_items_nominal');
}

$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();