可以在不重定向的情况下使用FlashMessenger吗?

问题描述 投票:0回答:2

我想知道是否可以在不重定向的情况下使用Flash Messenger?例如。登录失败后,我想继续显示表单,不需要重定向。

public function loginAction() {
  $form = new Application_Form_Login();

  ...

  if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getParams())) {
    $authAdapter = new Application_Auth_Adapter($form->getValue('username'), $form->getValue('password'));
    if ($this->auth->authenticate($authAdapter)->isValid()) {
      ...
    } else {
      // login failed
      $this->flashMessenger->addMessage('Login failed. You may have entered an invalid username and/or password. Try again');
    }
  }

  $this->view->form = $form;
}
php zend-framework
2个回答
9
投票

您可以使用 $this->flashMessenger->getCurrentMessages() 检索 Flash 消息而无需重定向; 示例:

$this->view->messages = array_merge(
    $this->_helper->flashMessenger->getMessages(),
    $this->_helper->flashMessenger->getCurrentMessages()
);
$this->_helper->flashMessenger->clearCurrentMessages();

3
投票

当然可以。但我通常将身份验证失败消息附加到表单本身。事实上,即使表单级验证失败,我也喜欢显示类似“请注意下面的错误”的内容。所以,我分别对待这两种情况:

public function loginAction()
{
    $form = new Application_Form_Login();
    if ($this->getRequest()->isPost()){
        if ($form->isValid($this->getRequest()->getPost())){
            $username = $form->getValue('username');
            $userpass = $form->getValue('userpass');
            $adapter = new Application_Model_AuthAdapter($username, $userpass);
            $result = $this->_auth->authenticate($adapter);
            if ($result->isValid()){
                // Success.
                // Redirect...
            } else {
                $form->setErrors(array('Invalid user/pass'));
                $form->addDecorator('Errors', array('placement' => 'prepend'));
            }
        } else {
            $form->setErrors(array('Please note the errors below'));
            $form->addDecorator('Errors', array('placement' => 'prepend'));
        }
    }
    $this->view->form = $form;
}
© www.soinside.com 2019 - 2024. All rights reserved.