当我尝试将表单的信息保存到数据库中时,我遇到了问题。即使在为所选网络中的每个影院手动设置影院的ID之后,我的表单似乎也没有效果。 这是我的模块的 actions.class.php :
的相关部分这是 executeCreate():
public function executeCreate(sfWebRequest $request) {
$this->form = $this->configuration->getForm();
$this->showing = $this->form->getObject();
$this->processCreateForm($request, $this->form);
$this->setTemplate('new');
}
现在 processCreateForm():
protected function processCreateForm(sfWebRequest $request, sfForm $form) {
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
$form_name = $form->getName();
$parameters = $request->getParameter($form_name);
$network_id = $parameters['network_id'];
$theaters_list = Doctrine_Query::create()
[...]
->execute();
foreach ($theaters_list as $theater) {
$form->getObject()->setTheaterId($theater->theater_id);
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid()) {
$showing = $form->save();
} else {
foreach ($form->getErrorSchema()->getErrors() as $key => $error) {
echo '<p>' . $key . ': ' . $error . '</p>';
}
}
}
$this->getUser()->setFlash('update_success', true);
$this->setTemplate('new');
}
这是输出:
感谢您的帮助
答案 0 :(得分:2)
这里有两件奇怪的事情,我想打破你的代码。
您运行bind()
方法两次,这可能会重置您对象的值。
我认为getObject()
方法不会通过引用返回对象。
所以当你跑:
$form->getObject()->setX($val);
$form->save();
然后更新表单返回的对象的字段,但保存仍然绑定到表单的原始对象。
尝试做这样的事情:
$myObject = $form->updateObject()->getObject();
$myObject->setX($value);
$myObject->save();
如果您使用表单编辑现有对象而不是创建新对象,则updateObject()
很重要。如果没有这个,你将得到对象的旧值。
如果要在循环中运行它,则只能循环设置和保存部分。所以你在processCreateForm
:
protected function processCreateForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid()) { //You can check the validity of your form at this point.
//Create $theatersList
...
$myObject = $form->updateObject();
foreach ($theatersList as $theater) {
$myObject->setTheaterId($theater->theater_id);
$showing = $myObject->save();
//Do something with $showing
}
} else {
//Print the errors.
}
}
使用此代码,您可以在表单中取消设置theatre_id
的窗口小部件,因为它不应由用户设置,也不必是表单验证的一部分。
修改强>
代码的一些更改:
protected function processCreateForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid()) { //You can check the validity of your form at this point.
//Create $theatersList
...
$myObject = $form->updateObject();
$myObjectVars = $myObject->toArray();
foreach ($theatersList as $theater) {
$myNewObject = new SomeClass();
$myNewObject->fromArray($myObjectVars);
$myNewObject->setTheaterId($theater->theater_id);
$showing = $myNewObject->save();
//Do something with $showing
$myNewObject->free();
unset($myNewObject);
}
} else {
//Print the errors.
}
}