Magento 在观察者中重新计算购物车总数
我有一个观察者,如果商品缺货(即客户每隔 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');
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
但是,如果您观察 quote 类中的collectTotals() 方法,那么您会发现您丢失了一个重要的标志
->setTotalsCollectedFlag(false)->collectTotals()
使得一旦计算完成就可以进行计算。如果您的荣耀之路上没有一些错误,生活将会有所不同,因此请注意 Magento 中的以下问题:问题#26145
However if you observe the collectTotals() method in quote class then you'll notice that you are missing a important flag
->setTotalsCollectedFlag(false)->collectTotals()
to make the calculation possible once it has been already calculated.Life would be something different if there were not some bugs in your path to glory so be aware of the following issue in Magento: Issue #26145
谢谢@Anton 的帮助!
最终对我有用的答案是在重定向之前(在观察者中)调用
session_write_close();
:Thank you @Anton for your help!
The answer that ended up working for me was to make a call to
session_write_close();
before the redirect (in the observer):下一个流程怎么样:
在
sales_quote_save_before
上删除观察者中的项目,并向注册表添加一些标志:Mage::register('ooops_we_need_a_redirect', $url)
在
sales_quote_save_after
上的观察者中,如果需要,请进行重定向:if (Mage::registry('ooops_we_need_a_redirect')) {
// 进行重定向
}
What about next flow:
Remove items in observer on
sales_quote_save_before
and add some flag to registry:Mage::register('ooops_we_need_a_redirect', $url)
In observer on
sales_quote_save_after
do redirect if needed:if (Mage::registry('ooops_we_need_a_redirect')) {
// do redirect
}