2012-05-04 54 views
0

我已经使用zend表单创建了一个表单,该表单位于applications目录中的表单目录中。我已经在控制器中创建这种形式的实例:将Zend_Form在视图中提交的数据传递给模型

public function getBookSlotForm(){ 
     return new Application_Form_BookSlot(); 
    } 
public function bookSlotAction() 
    { 
    $form = $this->getBookSlotForm(); 
    $this->view->form = $form; 
    } 

它显示给用户的视图:

echo $this->form; 

当用户在表单填写,我该怎么办我店模型中的变量中的数据?

回答

1

蒂姆到目前为止是正确的,但你似乎需要更多的细节。你似乎没有让你的表单显示在页面上的问题。现在,将表单中的数据存入您的控制器,然后再转到您想要的任何模型上,这非常简单直接。

我打算假设您在本示例的表单中使用了post方法。

当您在任何php应用程序中发布您的表单时,它会将其数据以阵列形式发送到$_POST变量。在ZF这个变量被存储在请求对象中的FrontController,并与$this->getRequest()->getPost()通常访问并且将返回值的相关联的阵列:使用延伸Zend_Form你应该访问自己的形式形成时

//for example $this->getRequest->getPost(); 
POST array(2) { 
    ["query"] => string(4) "joel" 
    ["search"] => string(23) "Search Music Collection" 
} 

//for example $this->getRequest()->getParams(); 
PARAMS array(5) { 
    ["module"] => string(5) "music" 
    ["controller"] => string(5) "index" 
    ["action"] => string(7) "display" 
    ["query"] => string(4) "joel" 
    ["search"] => string(23) "Search Music Collection" 
} 

作为特殊情况值将使用$form->getValues(),因为这将返回已应用了表单筛选器的表单值,因此getPost()getParams()将不会应用表单筛选器。

所以,现在我们知道我们是从发送值模型的过程中接收相当简单:

public function bookSlotAction() 
{ 
    $form = $this->getBookSlotForm(); 
    //make sure the form has posted 
    if ($this->getRequest()->isPost()){ 
     //make sure the $_POST data passes validation 
     if ($form->isValid($this->getRequest()->getPost()) { 
     //get filtered and validated form values 
     $data = $form->getValues(); 
     //instantiate your model 
     $model = yourModel(); 
     //use data to work with model as required 
     $model->sendData($data); 
     } 
     //if form is not vaild populate form for resubmission 
     $form->populate($this->getRequest()->getPost()); 
    } 
    //if form has been posted the form will be displayed 
    $this->view->form = $form; 
} 
0

典型的工作流程是:

public function bookSlotAction() 
{ 
    $form = $this->getBookSlotForm(); 
    if ($form->isValid($this->getRequest()->getPost()) { 
     // do stuff and then redirect 
    } 

    $this->view->form = $form; 
} 

调用的isValid()也将存储在表单对象中的数据,因此,如果验证失败,您的形式将与用户输入的填充数据再次显示

相关问题