【问题标题】:Possible to use FlashMessenger without redirect?可以在没有重定向的情况下使用 FlashMessenger 吗?
【发布时间】:2010-12-23 07:32:36
【问题描述】:

我想知道是否可以在没有重定向的情况下使用 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;
}

【问题讨论】:

    标签: zend-framework


    【解决方案1】:

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

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

    【讨论】:

    • 其实你根本不需要使用FMer。你可以写 $this->view->messages = array('my message', 'my message 2');
    • 有没有办法setCurrentMessages()?我不想总是显示所有消息。
    • 消息仅由 addMessage() 函数添加。 getMessages() 和 getCurrentMessages() 的区别在于前者用于获取重定向前保存在上一页的消息,后者可以检索在当前页面处理期间设置的消息。
    【解决方案2】:

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

    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;
    }
    

    【讨论】:

    • 我该怎么办?使用我上面的代码,flash messenger 消息只在刷新后显示
    • 这是我不喜欢 FlashMessenger 的地方之一;它仅驻留在控制器级别。对我来说,这个闪信业务应该是一个以视图为中心的过程。这就是为什么我主要使用名为priorityMessenger 的视图助手。要使现有的 FlashMessenger 有用,您可以查看Robert Basic's FlashMessenger view helper。在您的情况下,没有刷新,我仍然认为将错误附加到表单更简单。
    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 2012-03-21
    • 2013-05-28
    • 2015-12-27
    • 2011-02-15
    • 2011-04-09
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多