How does Flash Messages work in ZF 2?

1

I'm working with the Zend Framework 2.0 < />> I noticed that it has a helper to handle error messages, called "flashMessages", what I did not understand straight away is if it captures this by session, or by rendering the view, I'm breaking my head to use this helper, can someone tell me how I could implement this on a form?

Here is my method:

public function userDataAction() {

        $form = $this->getServiceLocator()->get('Admin\Service\FrmUserData');
        $form->setAttribute('action', $this->url()->fromRoute('user-admin', array('action' => 'persist-user')));

        $session = new Container('Admin\Service\FrmSearchUser');

        if (isset($session->data)) {

            $em = $this->getEm();
            $repository = $em->getRepository('Base\Model\Entity\Entities\Document');

            $document = $repository->findOneBy(
                    array(
                        'value' => $session->data['document_cpf'],
                        'type' => 'cpf'
                    )
            );

            if ($document instanceof \Base\Model\Entity\Entities\Document) {
                $user = $repository->searchUserById($document->getUser()->getIdUser());
                $repositoryUser = $this->getEm()->getRepository('Base\Model\Entity\Entities\User');

                $data = $repositoryUser->corrigiCampos($user);
            }
            $form->setData($data);
        }

        if ($this->getRequest()->isPost()) {

            $data = $this->getRequest()->getPost();
            $form->setData($data);
        }
          $messages = null;
        if ($this->flashMessenger()->hasMessages()) {
          /* aqui eu gostaria de setar as mensagens
           de saída como poderia fazer isso? */
           $messages = $this->flashMessenger()->getMessages();
        }

        return new ViewModel(
                array(
                  'form' => $form,
                  'title' => 'Consultar / cadastrar usuário',
                  'subTitle' => 'Preencha os dados abaixo',
                  'messages' => $messages
                )
        );
    }
    
asked by anonymous 05.01.2016 / 21:14

1 answer

1

The FlashMessenger plugin , sends your message to a Zend ( FlashMessenger Plugin ) pool that will appear in another page request (via ViewHelper FlashMessenger ).

You're wrong to send the variable to View , see below for how it works.

There are 4 types of messages that you can integrate with Bootstrap Notifications (error, info, default, success) .

Now let's practice

In your Action within Controller , you need to enter the message and its type:

use Zend\Mvc\Controller\Plugin\FlashMessenger;

public function registerAction(){
  if($formValid){
      $this->flashMessenger()->addSucessMessage('Registro Salvo!');
  } else{
      $this->flashMessenger()->addErrorMessage('Erro ao Salvar');
  }

  //redireciona para outra rota e só depois exibe
  return $this->redirect()->toRoute('app');
}

In View (.phtml), you only need to use:

#exibe mensagens do método addErrorMessage();
echo $flash->render('error',   array('alert', 'alert-dismissible', 'alert-danger'));
#exibe mensagens do método addInfoMessage();
echo $flash->render('info',    array('alert', 'alert-dismissible', 'alert-info'));
#exibe mensagens do método addMessage();
echo $flash->render('default', array('alert', 'alert-dismissible', 'alert-warning'));
#exibe mensagens do método addSucessMessage();
echo $flash->render('success', array('alert', 'alert-dismissible', 'alert-success'));

In View , if you have Bootstrap :

 $flash = $this->flashMessenger();
 $flash->setMessageOpenFormat('<div>
     <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
         &times;
     </button>
     <ul><li>')
     ->setMessageSeparatorString('</li><li>')
     ->setMessageCloseString('</li></ul></div>');


 echo $flash->render('error',   array('alert', 'alert-dismissible', 'alert-danger'));
 echo $flash->render('info',    array('alert', 'alert-dismissible', 'alert-info'));
 echo $flash->render('default', array('alert', 'alert-dismissible', 'alert-warning'));
 echo $flash->render('success', array('alert', 'alert-dismissible', 'alert-success')); 

Now Hack , if you want to display FlashMessages right on the screen without the request (Ideal for forms errors, in which you do not redirect or AJAX to another page), use renderCurrent, and do not forget to clean up.

echo $flash->renderCurrent('error',   array('alert', 'alert-dismissible', 'alert-danger'));

If you want to dig deeper into the subject, follow the links in the official Zend 2 documentation, give one an expert on the methods available, it will help a lot:

VIEW - > link

CONTROLLER - > link

    
21.02.2016 / 03:05