ZF2 namespace for flashmessenger

In my application I am using multiple forms, the forms submission points to another action but redirects back to the previous action. In the form submission action I handle the form input / validation. To return an error or success message I use the FlashMessenger.

My point of problem is that it's not clear how I set a namespace for the FlashMessenger. I have serval forms on the same page where I would like to use FlashMessenger messenges.

    if ($this->flashMessenger()->hasMessages()) {

      $messages = $this->flashMessenger()->getMessages();
      foreach($messages as $message) {
      echo $message;
      }

    } 

I am guessing I should do something with '$this->flashMessenger('namespace').. In my controller action? But I didn't figure out how exactly make this work. If anyone has an example.. that would be great :)

Answers


The namespace of the flash messenger controller plugin can be manual set using the setNamespace($namespace) method.

$this->flashMessenger()->setNamespace('foo')->addMessage($message);

However there are also convenience functions that will set a different namespace and message at the same time.

For example, if you want to add a success message then you can use:

$this->flashMessenger()->addSuccessMessage($message);

Internally the plugin will set the namespace as success and add the message to it (and then reset the namespace to allow for the next message to be set (defaults to default))

public function addSuccessMessage($message)
{
    $namespace = $this->getNamespace();
    $this->setNamespace(self::NAMESPACE_SUCCESS);
    $this->addMessage($message);
    $this->setNamespace($namespace);

    return $this;
}

You can add a message into a particular namespace by using these built-in methods in your action controller:

// in your controller
$this->flashMessenger()->addInfoMessage('info message');
$this->flashMessenger()->addSuccessMessage('success message');
$this->flashMessenger()->addErrorMessage('error message');

// in your view script
$this->flashMessenger()->getInfoMessages();
$this->flashMessenger()->getSuccessMessages();
$this->flashMessenger()->getErrorMessages();

Or if you want to specify your own namespace, you can use something like:

// in your action controller
$defaultNamespace = $this->getNamespace();
$this->setNamespace('yournamespace');
$this->addMessage($message);
$this->setNamespace($defaultNamespace);

// in your view script
$this->flashMessenger()->getMessagesFromNamespace('yournamespace');

For more information, you can see the documentation:

http://framework.zend.com/manual/2.3/en/modules/zend.mvc.plugins.html#flashmessenger-plugin http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.flash-messenger.html#basic-usage


Need Your Help