Symfony2, Doctrine, and forms - Persisting the data of both sides of a 1:* relationship in a single form

时光毁灭记忆、已成空白 提交于 2019-12-11 15:35:54

问题


In my Symfony2 project, I have a rather classic 1:* relationship with some of my entities (let's call them BlogPost and Comments, even though a NDC prevents me from saying what they really are). I've been tasked with modifying the form that currently exists to edit existing Comments so it can modify certain aspects of the BlogPost as well. I'm not entirely sure how to go about it, specifically with how Symfony2 and Doctrine handle their data binding.

Right now, I populate and bind to the form with (pseudo-code to protect the innocent):

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

As you can see, I already send the BlogPost to the view. And I know I can add it to the form by including it in my CommentsType class. I'm just not sure how to data bind it all properly.


回答1:


If you have the $blogPost, just persist it, the same as the comments. Also flush at the end:

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


来源:https://stackoverflow.com/questions/15977529/symfony2-doctrine-and-forms-persisting-the-data-of-both-sides-of-a-1-relat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!