【发布时间】:2012-02-06 22:06:36
【问题描述】:
我试试这本关于嵌入表单的食谱:
http://symfony.com/doc/current/cookbook/form/form_collections.html
但是嵌入的外键(Tag表中的task_id字段)没有保存,一直为NULL
完整代码如下:https://gist.github.com/1755140
你知道为什么吗? 谢谢
编辑:: 我的麻烦在于处理形式的行动。就像标签表单是动态嵌入的,所以我不知道我会有多少标签。如果我添加 createAction
$tag1 = new Tag();
$task->addTags($tag1);
只有第一个嵌入表单被正确保存!如何保存其他标签?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
编辑2:
我的解决方案解决了这个问题,你怎么看?更好?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
编辑3:
更好的选择(未再次测试)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
【问题讨论】: