dongtang5057 2013-08-07 17:01
浏览 12
已采纳

每页请求设置一次错误消息

I'm trying to create a minimum total checkout module that will prevent someone from checking out with a total less than a configurable amount.

I'm using the event sales_quote_save_before to display an error on the checkout/cart page when it's opened.

<?xml version="1.0"?>
<config>
    <frontend>
        <events>
            <sales_quote_save_before>
                <observers>
                    <b2b>
                        <class>b2b/observer</class>
                        <method>checkTotalsCart</method>
                    </b2b>
                </observers>
            </sales_quote_save_before>
        </events>
    </frontend>
</config>

And in the observer

public function checkTotalsCart()
{
    if ($this->_hasCartError()) { /* does some checks, returns bool */
        $this->_setErrorMessage();
    }
}
protected function _setErrorMessage()
{
    $session = Mage::getSingleton("b2b/session"); /* extends Mage_Core_Model_Session */
    $session->addError($this->helper->getErrorMessage());
}

The problem is that when you update the cart from the cart page, the error message is showing up twice. I guess that event is happening multiple times.

I've tried to check if the message was previously set with a custom session variable

protected function _setErrorMessage()
{
    $session = Mage::getSingleton("b2b/session");
    if ($session->hasErrorMessage()) {
        return;
    }
    $session->addError($this->helper->getErrorMessage());
    $session->hasErrorMessage(true);
}

But that didn't work either. How can I make sure an error message is only showing up once per page request?

  • 写回答

1条回答 默认 最新

  • douqiao5543 2013-08-08 07:33
    关注

    You must use $session->setErrorMessage(true); instead of $session->hasErrorMessage(true);, which is an isset()shortcut (both are magic methods, you can check Varien_Object::__call() to see what's their behaviour).

    But then the message will get displayed only once per session, so you could also detect if the message was already added by using this code :

    protected function _setErrorMessage()
    {
        $session = Mage::getSingleton('b2b/session'); /* extends Mage_Core_Model_Session */
        $errorMessage = $this->helper->getErrorMessage();
        $isMessageAdded = false;
    
        foreach ($session->getMessages() as $message) {
            if ($message->getText() == $errorMessage) {
                $isMessageAdded = true;
                break;
            }
        }
        if (!$isMessageAdded) {
            $session->addError($errorMessage);
        }
    
        return $this;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?