When working with form, you usually show a message after each action of users. Magento provides a very easy way to show error or success message. Below is an example:

How to do that? I’ll explain for you by creating a simple module called “Message”.

  • Step 1: Use ModuleCreator to create a module structure files.
  • Step 2: Create a model file called Session
    
    class Magestore_Message_Model_Session extends Mage_Core_Model_Session_Abstract {
    	public function __construct() {
    		$this->init('message');
    	}
    }
    
  • Step 3:
    
    <div class="page-head">
        <h3><?php echo $this->__('Demo for message control') ?></h3>
    </div>
    
    <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
    
    <?php
    	$type = 0;
    	if(isset($_GET['type']))
    	{
    		$type = $_GET['type'];
    	}
    ?>
    
    <form action="" method="get">
    <?php echo $this->__('Please choose message type: ') ?> <br/>
         <input type="radio" name="type" value="1" <?php echo ($type==1)?"checked='checked'":"" ?>> <?php echo $this->__('Error message ') ?><br/>
    <input type="radio" name="type" value="2" <?php echo ($type==2)?"checked='checked'":"" ?>> <?php echo $this->__('Success message ') ?>
    
    <input type="submit" name="submit" value="Submit">
    </form>
    

    In that file, you can see a piece of code to display the message:

    $this->getMessagesBlock()->getGroupedHtml();
  • Step 4: Edit action index in Magestore_Message_IndexController
    
    $type = $this->getRequest()->getParam('type');
    
    if(!empty($type))
    {
    switch($type)
    {
    case 1:
    Mage::getSingleton('message/session')->addError($this->__('You have choosen error option'));
    
    break;
    
    case 2:
    Mage::getSingleton('message/session')->addSuccess($this->__('You have choosen success option'));
    
    break;
    }
    }
    
    $this->loadLayout();
    
    $this->_initLayoutMessages('message/session');
    
    $this->renderLayout();
    }
    }
    

    Please look at three bold lines in the code above.

    Finish!!!

     

    How to pass Magento certification exam

Author

Why Magestore? We believe in building a meaningful & long-term relationship with you.

1 Comment

Write A Comment