flashmessenger doesn't show new messages

1.4k Views Asked by At

I'm using flashMesssenger in Zend Framework 2.2.0 to deliver messages from one action to another.

I have a Contact Us form that after it's exeuted i send an email and forward the user to the home page.

public function contactUsExecuteAction() {
    $request = $this->getRequest();
    if ($request->isPost()) {
        $contactUs = new ContactUs();
        $form = new ContactUsForm();
        $form->setInputFilter($contactUs->getInputFilter());
        $form->setData($request->getPost());
        if ($form->isValid()) {
            $contactUs->exchangeArray($form->getData());
            $name = $contactUs->name;
            $email = $contactUs->email;
            $message = $contactUs->message;
            $completeMessage='name:'.$name."\n".'email:'.$email."\n".$message;
            $subject = 'myalcoholist contact us';
            mail('<EMAIL_ADDRESSS>',$subject,$completeMessage);
            $this->flashMessenger()->addMessage("thank you for contacting myalcoholist.");

            return $this->forward()->dispatch('home');
        }

    }
  } 

now I understand that forward just forwards the page and i'm supposed to get the message only in the next iteration, unless i use getCurrentMessages. so this is in my layout.phtml

<?php 
 use Zend\Mvc\Controller\Plugin\FlashMessenger;

 $messenger = $this->flashMessenger()->getPluginFlashMessenger();
 foreach(array(
    FlashMessenger::NAMESPACE_ERROR,
    FlashMessenger::NAMESPACE_SUCCESS,
    FlashMessenger::NAMESPACE_INFO,
    FlashMessenger::NAMESPACE_DEFAULT)
    as $namespace):

$messenger->setNamespace($namespace);
$userMsgs = array_merge($messenger->getCurrentMessages(), $messenger->getMessages());
$messenger->clearCurrentMessages();

foreach($userMsgs as $msg):
    $msgText = $msg;
    if (is_array($msg)){
        $msgText = $msg['message'];
    }
    ?>
    <div class="alert alert-<?=$namespace?>">
        <?=$msgText?>
    </div>
 <?php endforeach ?>
<?php endforeach ?>

but for some reason I get no messages! it does forward the user properly but that's about it.

any ideas ?

1

There are 1 best solutions below

3
Andrew On BEST ANSWER

1)

Don't use forward, there will be no new request made.

Try just using a redirect, that way you will get a new request made and will find the messages waiting for you and you should not need any extra code to get it working.

$this->redirect()->toRoute('routeName');

or

$this->redirect()->toUrl('http://google.com/');

2)

If you are dertermined to use it in the view like that then you can always make a simple View Helper:

namespace Application\View\Helper;

use Zend\Mvc\Controller\Plugin\FlashMessenger as ZendFlash;
use Zend\View\Helper\AbstractHelper;

class FlashMessenger extends AbstractHelper
{
    /**
     * @var \Zend\Mvc\Controller\Plugin\FlashMessenger
     */
    protected $flashMessenger;
    /**
     * @var array
     */
    protected $namespaces = array(
        'default',
        'error', 
        'success',
        'info', 
        'warning'
    );

    /**
     * Set the Controller plugin
     * 
     * @param   Zend\Mvc\Controller\Plugin\FlashMessenger
     */
    public function setFlashMessenger($flashMessenger)
    {
        $this->flashMessenger = $flashMessenger;

        return $this;
    }

    /**
     * @return  string
     */
    public function __invoke()
    {
        $messageString = '';            
        foreach($this->namespaces as $ns) {
            $this->flashMessenger->setNamespace($ns);
            $messages = $this->flashMessenger->getMessages();
            if($this->flashMessenger->hasCurrentMessages()) {
                $messages += $this->flashMessenger->getCurrentMessages();
                $this->flashMessenger->clearCurrentMessages();
            }

            if(count($messages) > 0) {
                // Twitter bootstrap message box
                $messageString .= sprintf(
                    '<div class="container-fluid">
                        <div class="alert alert-%s fade in">
                            <button data-dismiss="alert" class="close" type="button">×</button>
                            %s
                        </div>
                    </div>',
                    $ns,
                    implode('<br />', $messages)
                );
            }
        }

        return $messageString;
    }
}

And now Inject the Flash Controller plugin in the Service Manager:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'flashMessenger' => function($sm) {      
                $flash = $sm->getServiceLocator()
                    ->get('ControllerPluginManager')
                    ->get('flashmessenger')
                ;
                $messages  = new \Application\View\Helper\FlashMessenger();
                $messages->setFlashMessenger($flash);

                return $messages;
           },

Now you can use the view helper inside the view much nicer:

example.phtml

<?php echo $this->flashMessenger() ?>