It looks like you are writing and reading the messages in the same request.
Think that flashMessenger is mainly meant to save messages for later, as you can read in the old but meaningful ZF1 docs:
The FlashMessenger helper allows you to pass messages that the user
may need to see on the next request.
For example, you are in a request that comes from a form that is meant to add records to a list, in the controller/action that receives the form you save a record, write the message to the flashmessenger
, and redirect the user to the controller/action that show the list of records again.
Something that you can see in this example from the ZF2 mvc plugins docs:
public function processAction()
{
// ... do some work ...
$this->flashMessenger()->addMessage('You are now logged in.');
return $this->redirect()->toRoute('user-success');
}
public function successAction()
{
$return = array('success' => true);
$flashMessenger = $this->flashMessenger();
if ($flashMessenger->hasMessages()) {
$return['messages'] = $flashMessenger->getMessages();
}
return $return;
}
If what you need is to read the messages in the same request (something that is also really common) you have to use the "Current Messages" methods of the helper. So, instead of calling
$this->flashMessenger()->hasSuccessMessages()
you should call
$this->flashMessenger()->hasCurrentSuccessMessages()
and instead of calling
$this->flashMessenger()->getSuccessMessages()
you should call
$this->flashMessenger()->getCurrentSuccessMessages()
You can take a look at the full list of functions, if you go to the Zend.Mvc.Controller.Plugin.FlashMessenger API docs and you search for "Current"
UPDATE
To show the messages in the view, you can use 2 approaches:
Retrieve the messages in the controller and send it to the view
In the controller
public function yourAction() {
return array (
'$successMessages'
=> $this->flashMessenger()->getCurrentSuccessMessages()
);
}
In the view
//note that getCurrentSuccessMessages() returns an array,
//so in the vew $successMessages is an array
foreach ($successMessages as $m) {
echo $m;
}
Retrieving directly in the view. The first thing that comes to mind is to use the FlashMessenger view helper (Zend\View\Helper \FlashMessenger
), but im afraid it doesnt have a function to get the current messages. So, you can extend it, or even more, you can write your own view helper. You have here a good tutorial on how to do exactly this.