Zend Form工作不正常,可以';我不理解文档的概念


Zend Form not working properly, can't understand the concept of documentation

我是zend的新生。正在浏览zend表单文档,有一件事无法理解。与oracle在zend上有一个项目,所以我的生活已经一团糟;-)。我被Zend_Form类的一些基本问题所困扰。问题是:当我们在操作中设置一个表单,并且它只发布回该操作时,显然会创建新的表单对象,我发布的值会像烟雾一样消失。那么如何让他们活着。我得到了$this->getrequest()->getparams()的替代品,但在zend文档中以及我所看到的示例中,它们都有相同的流程。他们没有使用getparams()作为选项。让我把它通过代码,得到非常清楚的想法。

public function indexAction()
    {
        $this->view->title = 'Welcome to CashTray ';       // passing title to view
        // creating cashtray mapper object
        $cashTrayMapper = new Application_Model_CashtrayMapper();
        // search form object
/* It will reset the object, a obvious thing*/
            $searchForm = new Application_Form_Cashtray_Search();                       // creating search form object
        if ($this->getRequest()->isPost())                                          // post request found
        {
            var_dump($searchForm->getValues(), $this->getRequest()->getparams());die;                
        }
        else
        {
            $this->view->form = $searchForm;
            // retrieving cashtray list
            $this->view->entries = $cashTrayMapper->fetchAll();                               // passing form to view
        }

    }

输出:

array(2) { ["client"]=> string(0) "" ["offset"]=> string(0) "" } 
array(6) { ["controller"]=> string(8) "cashtray" ["action"]=> string(5) "index" ["module"]=> string(7) "default" ["client"]=> string(4) "1001" ["offset"]=> string(3) "214" ["submit"]=> string(6) "Search" } 

现在我们可以看到表单已经发布,值也在那里,但为什么我不能通过$searchForm->getValues();获得它。在示例中,他们使用$form而不是$searchForm,我认为这不应该是问题所在。

典型的工作流程更像这样:

public function indexAction()
{
    $this->view->title = 'Welcome to CashTray ';       // passing title to view
    // creating cashtray mapper object
    $cashTrayMapper = new Application_Model_CashtrayMapper();
    // search form object
    $searchForm = new Application_Form_Cashtray_Search();                       // creating search form object
    if ($this->getRequest()->isPost()) {
        if ($searchForm->isValid($this->getRequest()->getPost()) {
            // do stuff and then redirect
        }
    }
    $this->view->form = $searchForm;
    // retrieving cashtray list
    $this->view->entries = $cashTrayMapper->fetchAll();
}

这样,如果表单验证失败,数据仍在表单对象中,并将与相关错误一起重新显示。

您必须使用$searchForm->isValid($this->getRequest()->getPost())加载(并验证)Zend_Form中的值。

正如其他人所指出的,调用$form->isValid($this->getRequest()->getPost())会用POST数据填充表单,还会用过滤器过滤值,如果不符合验证规则,还会添加错误。

我想补充的是,您还可以通过调用$form->populate($data)来设置表单值,其中$data是一个名称与您的输入名称匹配的数组。如果您有用于编辑现有实体的表单,并且希望预先填充它们,那么这很方便。与isValid()不同,这不使用验证器执行任何检查。