Zend形式:验证失败后如何恢复正确的视图?

时间:2012-07-26 07:57:44

标签: forms validation zend-framework

我在使用Zend表单验证失败后重新显示视图时出现问题。

我的初步行动似乎是

public function test1Action() {
    // get a form and pass it to the view
    $this->view->form = $this->getForm(); 

    // extra stuff I need to display 
    $this->view->name = "Bob";
}

和视图

Hello <?= $this->name?>
<?php echo $this->form;?>

当行动&#34; test2&#34;在提交表单后调用有一个验证错误:

public function test2Action() {
    if (!$this->getRequest()->isPost()) {
        return $this->_forward('test1');
    }

    $form = $this->getForm();
    if (!$form->isValid($_POST)) {
        $this->view->form = $form;
        return $this->render('test1'); // go back to test1
    }
}

确实,变量&#34; name&#34;丢失,视图不正确。而不是说&#34; Hello Bob&#34;它说&#34;你好&#34;。

我应该如何处理?我应该重定向到test1而不是再次渲染test1吗?怎么样 ?

修改

根据科德先生的回答,以下是我最终的结果:

控制器:

    public function getForm() {
        // what is important is that the form goes to action test3 and not test4
        // SNIP form creation with a field username
        return $form;
    }

    public function test3Action()
    {
        $this->view->form = $this->getForm();
        $this->view->name = "Bob";

        if(!$this->getRequest()->isPost())return;

        if($this->view->form->isValid($_POST))
        {
            //save the data and redirect
            $values = $this->view->form->getValues();
            $username = $values["username"];

            $defaultSession = new Zend_Session_Namespace('asdf');
            $defaultSession->username = $username;

            $this->_helper->redirector('test4');
        }
    }


    public function test4Action()
    {
        $defaultSession = new Zend_Session_Namespace('asdf');
        $this->view->username = $defaultSession->username;
    }

test3.phtml

Hello <?= $this->name?>
<?php echo $this->form;?>

test4.phtml

success for <?php echo $this->username;?>

1 个答案:

答案 0 :(得分:1)

带回你的鲍勃

public function test2Action() {
    if (!$this->getRequest()->isPost()) {
        return $this->_forward('test1');
    }

    $form = $this->getForm();
    if (!$form->isValid($_POST)) {
        $this->view->form = $form;
        $this->view->name = 'bob';        
        return $this->render('test1'); // go back to test1
    }
}

但我会建议我的处理形式的解决方案,如

public function test2Action()
{

   $this->view->form = new My_Form();

   if(!$this->getRequest()->isPost())return;   

  if($this->view->form->isValid())
   {
    //save the data and redirect 
       $this->_helper->redirector('success');
   }

  }

在你的test2.phtml里面

<?php echo $this->form ?>

}

这种方法可以避免创建多个操作来保存一个表单并手动更改视图。