将视图中Zend_Form提交的数据传递给模型


Pass data submitted by Zend_Form in the view to the model

我使用 zend form 创建了一个表单,该表单位于应用程序目录的表单目录中。我在控制器中创建了此表单的实例:

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

并在视图中向用户显示:

echo $this->form;

当用户填写表单时,如何将该数据存储在模型的变量中?

就他而言,蒂姆是正确的,但你似乎需要更多的细节。 您似乎对在页面上显示表单没有问题。现在,将数据从该表单获取到控制器中,然后获取到您想要的任何模型非常简单.

我假设您在此示例中使用表单中的 post 方法.

当您在任何 php 应用程序中发布表单时,它会将其数组形式的数据发送到 $_POST 变量。在 ZF 中,此变量存储在请求对象的前端控制器中,通常使用 $this->getRequest()->getPost() 进行访问,并将返回一个关联的值数组:

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

作为特殊情况,当使用扩展Zend_Form的表单时,您应该使用$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;
}

典型的工作流程是:

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

调用isValid((也会将数据存储在表单对象中,因此如果验证失败,您的表单将重新显示,并填写用户输入的数据。