Hello Universe
Hello Universe

Reputation: 3302

How do you show message from controller to view in magento?

I will like to show message from controller to view in magento. In controller I have

    $arrError=Mage::getModel('advert/advert')->isValid(array('step1','step2'));
        if (!empty($arrError)) {
            $strReturnPath = $arrError['return_path'];
            unset($arrError['return_path']);
            foreach ($arrError as $strError) {
                Mage::getSingleton('customer/session')->addError( $strError );
                //var_dump($strError);

            }

            $this->_redirect($strReturnPath);
        }

        $this->loadLayout();
        $this->_initLayoutMessages('customer/session');

        $this->renderLayout();

And in view I have

<div id="messages_product_error_view">
    <?php

        Mage::app()->getLayout()->getMessagesBlock()->setMessages(Mage::getSingleton('customer/session')->getMessages(true));
        echo  Mage::app()->getLayout()->getMessagesBlock()->toHtml();
    ?>
</div>

In controller when I do a var_dump I can see the error messages. With redirect, the page does redirect to the view page. However, in the div I expect the message to be shown. ANd it is not showing Please please please help?

Upvotes: 0

Views: 1772

Answers (3)

Hello Universe
Hello Universe

Reputation: 3302

Mage::app()->getLayout()->getMessagesBlock()->setMessages(Mage::getSingleton('customer/session')->getMessages(true));

was resetting my session . As a result, I was lossing the messages. Crap! Damn! Bugger!

Anyway, by removing the line I have the solution working.

Upvotes: 0

Zefiryn
Zefiryn

Reputation: 2265

I think _redirect() method in controller does not stop script execution. It only sets up redirect headers. Because of that it still process loading layout, initializing layout messages and rendering it. This will make magento read messages in the same process and clear them before the actual redirect. Try adding this code after calling _redirect() method

$this->getResponse()->sendResponse();

or rearrange your code in this manner:

if (!empty($arrError)) {
        $strReturnPath = $arrError['return_path'];
        unset($arrError['return_path']);
        foreach ($arrError as $strError) {
            Mage::getSingleton('customer/session')->addError( $strError );
            //var_dump($strError);

        }

        $this->_redirect($strReturnPath);
    }
 else {
    $this->loadLayout();
    $this->_initLayoutMessages('customer/session');

    $this->renderLayout();
 }

Upvotes: 1

sambolekpetar
sambolekpetar

Reputation: 11

When you debug Mage::getSingleton('customer/session')->getMessages(true) in your view, does it contain any of the messages?

If you want to understand Magento notification better, you may find more about it here.

Upvotes: 0

Related Questions