Symfony2如何处理动态嵌入表单集合?

时间:2012-02-06 22:06:37

标签: php forms symfony

我尝试这本关于嵌入形式的食谱:
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()
    ); 
}

EDIT2:

我解决问题的解决方案,您如何看待它?更好?

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()
        );
}

EDIT3:

更好的替代方案(未再次测试)
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()
    );
}

2 个答案:

答案 0 :(得分:0)

在第29行的TaskController中尝试使用$task->addTags($tag1);代替$task->getTags()->add($tag1);

答案 1 :(得分:0)

我不明白。这个解决方案有误吗?

if ($form->isValid()) {
    $em = $this->getDoctrine()->getEntityManager();
    foreach($task->getTags() as $tag) {
        $tag->setTask($task);
    }
    $em->persist($task);
    $em->flush();

    return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));   
}

它有效并且看起来更简单。