在我的Zend应用程序中,我为每个表都有单独的模型,并使用TableGateway
现在我需要实现表单来创建编辑页面。我可以创建http://framework.zend.com/manual/2.2/en/user-guide/forms-and-actions.html
中提到的一个表/模型的形式这是我的编辑操作 -
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('candidate', array(
'action' => 'index'
));
}
try {
$candidate = $this->getCandidateTable()->getCandidate($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('candidate', array(
'action' => 'index'
));
}
$form = new CandidateForm();
$form->bind($candidate);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($candidate->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getCandidateTable()->saveCandidate($candidate);
return $this->redirect()->toRoute('candidate');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
编辑视图 -
<?php
$title = 'Edit Candidate';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'candidate',
array(
'action' => 'edit',
'id' => $this->id,
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
此编辑操作将表单与一个表(CandidateTable)绑定。但在我的应用程序中,该页面包含来自多个表格的数据(CandidateSkills,CandidateQualifications等)。当我点击提交时,它应该将数据保存在单独的表中。
答案 0 :(得分:1)
您可以使用setFromArray
您获取行对象而不仅仅是 setFromArray 并保存,提交。
要填充表单值,请使用populate方法,请参阅此Populating and Retrieving Values
$form = new My_Form_Edit();
if( !$this->getRequest()->isPost() )// If the form isn't posted than populate the value
{
$form->populate($myArrayValueToPopulate);//$myArrayValueToPopulate this is your array to populate for the form
return;
}
// Than check validation and save data
对于zend framework 2,您可以使用bind来填充数据Binding an object
直接来自文档
将对象绑定到表单时,会发生以下情况:
这在实践中更容易理解。
$contact = new ArrayObject;
$contact['subject'] = '[Contact Form] ';
$contact['message'] = 'Type your message here';
$form = new Contact\ContactForm;
$form->bind($contact); // form now has default values for
// 'subject' and 'message'
$data = array(
'name' => 'John Doe',
'email' => 'j.doe@example.tld',
'subject' => '[Contact Form] \'sup?',
);
$form->setData($data);
if ($form->isValid()) {
// $contact now looks like:
// array(
// 'name' => 'John Doe',
// 'email' => 'j.doe@example.tld',
// 'subject' => '[Contact Form] \'sup?',
// 'message' => 'Type your message here',
// )
// only as an ArrayObject
}