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)
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.
or
2)
If you are dertermined to use it in the view like that then you can always make a simple View Helper:
And now Inject the Flash Controller plugin in the Service Manager:
Now you can use the view helper inside the view much nicer:
example.phtml