简体   繁体   English

Symfony2-嵌入式表单擦除子数据

[英]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. 因此,我首先可以显示一个包含BlogPost及其相关注释的表单。 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. 问题是,如果我编辑一些BlogPost信息并保存,它将清除我的所有评论,无论它们是否与 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: 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. 我看不到为什么保存BlogPost信息会擦除任何评论,更不用说不属于该特定帖子的评论了。

You are using cascade={"all"} on the OneToMany relationship between Comment and BlogPost . 您正在CommentBlogPost之间的OneToMany关系上使用cascade={"all"}

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() ): 您无需手动persist博客文章中发布的评论,因此可以从控制器中删除以下代码(在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 有关该主题的学说文档: https : //doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html?highlight= Transitive%20Persistence#transitive-persistence-cascade- operations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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