0

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

当提交表单后调用的操作“test2”出现验证错误时,问题就出现了:

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

实际上,变量“名称”丢失了,视图不正确。它不是说“Hello Bob”,而是说“Hello”。

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

编辑

根据 Coder 先生的回答,我得到了以下结果:

控制器:

    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;?>
4

1 回答 1

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 ?>

}

这种方法使您免于创建多个操作来保存一个表单和手动更改视图。

于 2012-07-26T08:46:14.363 回答