我是Zend Framework的新手,我正在尝试检索一些值来更新数据库。我在控制器中有以下代码。填充表单工作得很好,用一些硬编码的值更新数据库也是如此。我的问题在于试图从表单中检索更新的值,请参阅$first_name变量。这给了我一个致命的错误。
我的问题是:如何从表单中检索更新的值?
public function editAction() {
$view = $this->view;
//get the application
$application_id = $this->getRequest()->getParam('id');
$application = $this->getApplication($application_id);
//get the applicant
$applicant_id = $application->applicant_id;
$applicant = $this->getApplicant($applicant_id);
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('Save')) {
$applicants_table = new Applicants();
$first_name = $form->getValue('applicant_first_name');
$update_data = array ('first_name' => 'NewFirstName',
'last_name' => 'NewLastName');
$where = array('applicant_id = ?' => 16);
$applicants_table->update($update_data, $where);
}
$url = 'applications/list';
$this->_redirect($url);
} else { //populate the form
//applicant data
$applicant_data = array();
$applicant_array = $applicant->toArray();
foreach ($applicant_array as $field => $value) {
$applicant_data['applicant_'.$field] = $value;
}
$form = new FormEdit();
$form->populate($applicant_data);
$this->view->form = $form;
}
}
首先,您的示例在这里有一个问题:
$first_name = $form->getValue('applicant_first_name');
您的$form
尚未创建,因此出现致命错误;您正在对非对象调用getValue()
。
一旦得到平方,就可以通过使用请求数据调用$form
上的isValid
方法,用发布的数据填充表单。这里有一个快速的例子:
// setup $application_data
$form = new FormEdit();
$form->populate($applicant_data);
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$first_name = $form->getValue('applicant_first_name');
// save data to the database ...
}
}