How does Flash Messages work on ZF 2?

Asked

Viewed 756 times

1

I’m working with the Zend Framework 2.0 and I noticed that he has a helper for handling error messages, called "flashMessages", which I didn’t understand straight away is whether he captures this by session, or by rendering the view, I’m cracking my head to use this helper, someone can tell me how I could implement this in 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
                )
        );
    }

1 answer

1


The Flashmessenger Plugin, sends your message to a waiting pool (through the Flashmessenger Plugin MVC of Zend) which will be displayed in another page request (through Viewhelper Flashmessenger).

You are wrong to send the variable to View, see below how it works.

There are 4 types of messages you can integrate with Bootstrap notifications (error, info, default, Success).

Now let’s practice

In his Action within the Controller, you need to inform 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 the 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 the View, if using 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 go a Hack, if you want to display the Flashmessages logo on screen without the request (Ideal for form errors, where you don’t redirect or AJAX to another page), use renderCurrent, and don’t forget to clean.

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

If you want to delve deeper into the subject, follow the links of the Official Zend 2 documentation, give a try on the methods available, will help a lot:

VIEW -> http://framework.zend.com/manual/current/en/modules/zend.view.helpers.flash-messenger.html

CONTROLLER -> http://framework.zend.com/manual/current/en/modules/zend.mvc.plugins.html#zend-mvc-controller-plugins-flashmessenger

Browser other questions tagged

You are not signed in. Login or sign up in order to post.