Zend Form工作不正常,无法理解文档的概念

时间:2012-03-23 12:00:30

标签: php zend-framework zend-form

我是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我不知道我认为应该是问题。

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

正如其他人所说,调用$form->isValid($this->getRequest()->getPost())会使用POST数据填充表单,也会使用过滤器过滤值,并在不符合验证规则时添加错误。

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