i wonder if many of my pages may use a FlashMessenger, whats the best way to automatically render out all messages say at the top of the page (like those here in SO, telling the user they got a badge etc)
views:
33answers:
2
A:
You could use a preDispatch-Plugin to inject the content of the FlashMessenger into your view and output it in your layout template.
Benjamin Cremer
2010-07-26 14:38:19
i am trying to do that, but how do i access the flashMessenger from the plugin?
jiewmeng
2010-07-31 13:29:50
Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
Benjamin Cremer
2010-08-01 10:46:57
+2
A:
I have this view helper:
<?php
class Zf_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
{
/**
* @var Zend_Controller_Action_Helper_FlashMessenger
*/
private $_flashMessenger = null;
/**
* Display Flash Messages.
*
* @param string $key Message level for string messages
* @param string $template Format string for message output
* @return string Flash messages formatted for output
*/
public function flashMessenger($key = 'success',
$template='<div id="flash-message" style="display:none"><p class="%s">%s</p></div>')
{
$flashMessenger = $this->_getFlashMessenger();
//get messages from previous requests
$messages = $flashMessenger->getMessages();
//add any messages from this request
if ($flashMessenger->hasCurrentMessages()) {
$messages = array_merge(
$messages,
$flashMessenger->getCurrentMessages()
);
//we don't need to display them twice.
$flashMessenger->clearCurrentMessages();
}
//initialise return string
$output ='';
//process messages
foreach ($messages as $message)
{
if (is_array($message)) {
list($key,$message) = each($message);
}
$output .= sprintf($template,$key,$message);
}
return $output;
}
/**
* Lazily fetches FlashMessenger Instance.
*
* @return Zend_Controller_Action_Helper_FlashMessenger
*/
public function _getFlashMessenger()
{
if (null === $this->_flashMessenger) {
$this->_flashMessenger =
Zend_Controller_Action_HelperBroker::getStaticHelper(
'FlashMessenger');
}
return $this->_flashMessenger;
}
}
In my controller I have this:
if($form->isValid($formData))
{
$Model = $this->getModel();
$id = $Model->add($formData);
$this->_helper->flashMessenger('The category has been inserted.');
$this->_helper->redirector('list');
}
So, in my view I just echo the helper:
<?php echo $this->flashMessenger(); ?>
Keyne
2010-07-26 17:12:21