Thursday, January 19, 2012

Zend Flash message

For displaying flash message after certain event like, when user submit the page and need to show the success message in next request or in current request. For that Zend framework has a action helper FlashMessenger.

Here is a sample code that can used to flash the message.

Step 1: Add message to helper class in controller

$flash = $this->_helper->getHelper('FlashMessenger');
$flash->addMessage(array('success' => 'Posted message saved successfully' ));

Ste 2: Create View Helper to display message in layout

class Custom_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
{
public function flashMessenger ($width = null)
{
$flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

#for message
$message = array();

if($flash->getCurrentMessages())
{
foreach($flash->getCurrentMessages() as $key => $msg)
{
$message[key($msg)][] = $msg[key($msg)];
}

$flash->clearCurrentMessages();
}
else if($flash->getMessages())
{
foreach($flash->getMessages() as $key => $msg)
{
$message[key($msg)][] = $msg[key($msg)];
}
}

$str_msg = null;
$style = '';

if($width) $style = "style='width:".$width."px'";

if(count($message) > 0)
{
foreach($message as $key => $arr_msg)
{
$key = ($key == 'error')?'errormsg':$key;

$str_msg .= '
';
$str_msg .= '

';

foreach($arr_msg as $msg)
{
$str_msg .= rtrim($msg,'.'). "
";
}
$str_msg .= '

';
$str_msg .= '
';
}
}

return $str_msg;
}

public function hasMessage()
{
$flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

if($flash->hasMessages() || $flash->hasCurrentMessages())
return true;
else
return false;
}
}

Step 3: Display the message in layout




echo $this->flashMessenger();


Now you can add your falsh message in you any controller and it will display in you layout.

Hope this helps someone.

1 comment:

  1. very nice ! use this structure but with an extra hasCurrentMessages/hasMessages condition

    ReplyDelete