简体   繁体   中英

Symfony2 - Embedded forms wipe child data

Yet another continuation of this and also this :

So, I'm able to initially show a form that contains a BlogPost and it's associated Comments. The problem is, if I edit some BlogPost info and save, it wipes out all of my Comments, regardless of whether or not they're related to that BlogPost. Not good.

Most of my relevant code is in the second link above, so I won't repeat it here. I will, however, add what's in my controller and view.

Controller:

public function EditBlogAction($id)
{
    $request = $this->get('request');
    $em = $this->get('doctrine')->getManager();
    $blogPost = $em->getRepository('Acme\SiteBundle\Entity\BlogPost')->find($id);

    $comments = $blogPost->getComments();

    $form = $this->createForm(new BlogPostType(), $blogPost);

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

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

        $em->flush();
        $em->clear();
    }

    return $this->render('SiteBundle:Site:editblog.html.twig',array('blogpost' => $blogPost, 'form' => $form->createView()));
}

editblog.html.twig:

<form action='{{ path('_admin_blog_edit', { 'id':blogpost.getId }) }}' method='post' enctype="multipart/form-data">
    {{ form_widget(form.title) }}

    {# other blog post fields #}

    {% for comment in form.comments %}
        {{ comment.commentBody }}
    {% endfor %}
<input type="submit" />

I can't see why saving BlogPost info would wipe any Comments, let alone Comments not belonging to that particular post.

You are using cascade={"all"} on the OneToMany relationship between Comment and BlogPost .

You don't need to manually persist the comments posted with your blog post, so you can remove the following code from your controller (in EditBlogAction() ):

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

Doctrine documentation on the subject: https://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html?highlight=Transitive%20Persistence#transitive-persistence-cascade-operations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM