0

在我的 Symfony2 项目中,我与我的一些实体有一个相当经典的 1:* 关系(我们称它们为 BlogPost 和 Comments,尽管 NDC 阻止我说出它们的真正含义)。我的任务是修改当前存在的表单以编辑现有评论,以便它也可以修改 BlogPost 的某些方面。我不完全确定如何去做,特别是 Symfony2 和 Doctrine 如何处理它们的数据绑定。

现在,我使用(保护无辜者的伪代码)填充并绑定到表单:

Grab the BlogPost based on the incoming request ID
Grab all Comments related to BlogPost

$form = $this->createForm(new CommentsType(), array('comments' => $comments));

if ($request->getMethod() == "POST")
{
    $form->bind($request);

    foreach($comments as $comment) {
        $doctrine->persist($comment);
    }
}

return $this->render('blah.html.twig', array('blog' => $blogPost, 'comments' => $comments, 'form' => $form->createView());

如您所见,我已经将 BlogPost 发送到视图。而且我知道我可以通过将它包含在我的 CommentsType 类中来将它添加到表单中。我只是不确定如何正确绑定数据。

4

1 回答 1

2

如果你有$blogPost,就坚持下去,和评论一样。最后也冲洗:

$form = $this->createForm(new CommentsType(), array('comments' => $comments));

if ($request->getMethod() == "POST")
{
    $form->bind($request);

    foreach($comments as $comment) {
        $doctrine->persist($comment);
    }
    $doctrine->persist($blogPost);
    $doctrine->flush();
}

return $this->render('blah.html.twig', array('blog' => $blogPost, 'comments' => $comments, 'form' => $form->createView());
于 2013-04-12T17:45:43.173 回答