Magento – How display success message after submit the form

customerformshelpermagento-1.8messages

How display success a message after submit the form.
This is my site a link

Best Answer

In php this type of work implement on session variable.

Magento is doing by

set success message using ->addSuccess('YOUR MSG');.

and set error message using ->addError('YOUR ERROR MSG')

Those magento functions are Object of

  1. Mage::getSingleton('core/session')

  2. Mage::getSingleton('customer/session')

  3. Mage::getSingleton('catalog/session')

So you can set this message.

  1. Mage::getSingleton('core/session')->addSuccess('YOUR MSG');
  2. Mage::getSingleton('customer/session')->addSuccess('YOUR MSG');

etc

This message is shown at phtml file using add below code:

<div id="messages_product_view"><?php echo $this->getMessagesBlock()->getGroupedHtml() ?></div>

Most Important Note:

This session message is one available up to one render.

ON Message display page ,you need to initialized this session using code initLayoutMessages() and you need add this code before $this->renderLayout(); function i.e Start of render layout

Just like:

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

Suppose you have set message at Mage::getSingleton('customer/session') and on message display page you have not initialized $this->_initLayoutMessages('customer/session');

Then you did not get this message.

A Good example is contact page:

public function postAction()
{
   ........
    if ( $post ) {
        $translate = Mage::getSingleton('core/translate');
        /* @var $translate Mage_Core_Model_Translate */
        $translate->setTranslateInline(false);
        try {
       .............
            Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
            $this->_redirect('*/*/');

            return;
        } catch (Exception $e) {
            $translate->setTranslateInline(true);

            Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
            $this->_redirect('*/*/');
            return;
        }

    } else {
        $this->_redirect('*/*/');
    }
}

Message is show at indexAction:

  public function indexAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('contactForm')
            ->setFormAction( Mage::getUrl('*/*/post') );

        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
        $this->renderLayout();
    }