سؤال

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?

هل كانت مفيدة؟

المحلول

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top