Symfony2表单实体更新

Jer*_*cks 24 forms entity symfony

谁能告诉我一个Symfony2表单实体更新的具体示例?本书仅介绍如何创建新实体.我需要一个如何更新现有实体的示例,其中我最初在查询字符串上传递实体的id.

我无法理解如何在检查帖子的代码中再次访问表单而无需重新创建表单.

如果我重新创建表单,这意味着我还必须再次查询该实体,这似乎没有多大意义.

这是我目前所拥有的,但它不起作用,因为它在表单发布时覆盖实体.

public function updateAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
    $form = $this->createForm(new TestimonialType(), $testimonial);

    $request = $this->get('request');
    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        echo $testimonial->getName();

        if ($form->isValid()) {
            // perform some action, such as save the object to the database
            //$testimonial = $form->getData();
            echo 'testimonial: ';
            echo var_dump($testimonial);
            $em->persist($testimonial);
            $em->flush();

            return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));
        }
    }

    return $this->render('MyBundle:Testimonial:update.html.twig', array(
        'form' => $form->createView()
    ));
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*cks 16

现在工作.不得不调整一些事情:

public function updateAction($id)
{
    $request = $this->get('request');

    if (is_null($id)) {
        $postData = $request->get('testimonial');
        $id = $postData['id'];
    }

    $em = $this->getDoctrine()->getEntityManager();
    $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
    $form = $this->createForm(new TestimonialType(), $testimonial);

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

        if ($form->isValid()) {
            // perform some action, such as save the object to the database
            $em->flush();

            return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));
        }
    }

    return $this->render('MyBundle:Testimonial:update.html.twig', array(
        'form' => $form->createView()
    ));
}
Run Code Online (Sandbox Code Playgroud)


小智 10

这实际上是Symfony 2的原生功能:

您可以从命令行自动生成CRUD控制器(通过doctrine:generate:crud)并重用生成的代码.

文档:http: //symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html

  • 我知道这是一篇旧文章,但我只需要感谢您!我仍然坐在这里像傻瓜一样编写我的CRUD代码!谢谢你,先生! (2认同)