Major Productions
Major Productions

Reputation: 6042

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

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.

Upvotes: 0

Views: 143

Answers (1)

Lighthart
Lighthart

Reputation: 3656

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

Upvotes: 2

Related Questions