Magento在观察者中重新计算购物车总数

Tob*_*ing 11 session magento cart observer-pattern

我有一个观察员,如果他们缺货就会从购物车中移除物品(即顾客返回购物车的时间x,购物车中的商品已经缺货),并向用户显示消息.

删除项目有效,但更新购物车总数不会. 任何帮助将非常感激!

我的观察者观察sales_quote_save_before事件:

public function checkStockStatus($observer)
{
    // return if disabled or observer already executed on this request
    if (!Mage::helper('stockcheck')->isEnabled() || Mage::registry('stockcheck_observer_executed')) {
        return $this;
    }

    $quote = $observer->getEvent()->getQuote();
    $outOfStockCount = 0;

    foreach ($quote->getAllItems() as $item) {
        $product = Mage::getModel('catalog/product')->load($item->getProductId());
        $stockItem = $product->getStockItem();
        if ($stockItem->getIsInStock()) {
            // in stock - for testing only
            $this->_getSession()->addSuccess(Mage::helper('stockcheck')->__('in stock'));
            $item->setData('calculation_price', null);
            $item->setData('original_price', null);
        }
        else {
            //remove item 
            $this->_getCart()->removeItem($item->getId());
            $outOfStockCount++; 
            $this->_getSession()->addError(Mage::helper('stockcheck')->__('Out of Stock'));
        }
    }

    if ($outOfStockCount) > 0) {       
        $quote->setTotalsCollectedFlag(false)->collectTotals();
    } 

    Mage::register('stockcheck_observer_executed', true);

    return $this;         
}

protected function _getCart()
{
    return Mage::getSingleton('checkout/cart');
}

protected function _getSession()
{
    return Mage::getSingleton('checkout/session');
}  
Run Code Online (Sandbox Code Playgroud)

Ant*_*n S 21

当天的提示:通过观察*_save_after并尝试强制改变同一个对象通常会再次调用save并最终进入无限循环 .oO

但是,如果您在引用类中观察到collectTotals()方法,那么您将注意到,您已经缺少一个重要的标志->setTotalsCollectedFlag(false)->collectTotals(),以便在计算完成后使计算成为可能.

如果你的荣耀之路上没有一些错误,生活会有所不同,所以要注意Magento中的以下问题:问题#26145


Tob*_*ing 6

谢谢@Anton 的帮助!

最终为我工作的答案是session_write_close();在重定向之前(在观察者中)拨打电话:

if (// products are out-of-stock and were removed...) {
    $this->_getSession()->addError('Error message here.');
    $this->_getSession()->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
    session_write_close();
    Mage::app()->getResponse()->setRedirect('index');
}
Run Code Online (Sandbox Code Playgroud)