phpzend-framework

Zend Framework: What shld i use to automatically render out messages if any from FlashMessenger


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)


Solution

  • 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(); ?>