11

我有一个观察者,如果商品缺货(即客户经常返回购物车 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');
}  
4

3 回答 3

21

当天提示:通过观察*_save_after并尝试强制更改相同的对象通常会再次调用 save并且您将最终陷入无限循环.oO

但是,如果您在 quote 类中观察 collectTotals() 方法,那么您会注意到您缺少一个重要标志->setTotalsCollectedFlag(false)->collectTotals(),以便在计算完成后进行计算。

如果在通往荣耀的道路上没有错误,生活将会有所不同,因此请注意 Magento 中的以下问题:问题 #26145

于 2011-10-04T07:37:52.360 回答
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');
}
于 2011-10-04T23:27:20.893 回答
0

下一个流程呢:

  1. 删除观察者中的项目sales_quote_save_before并向注册表添加一些标志:Mage::register('ooops_we_need_a_redirect', $url)

  2. 如果需要,在观察者上sales_quote_save_after做重定向:

    if (Mage::registry('ooops_we_need_a_redirect')) { // 做重定向 }

于 2011-10-04T21:11:46.653 回答