Symfony2表单实体更新 [英] Symfony2 Form Entity Update

查看:69
本文介绍了Symfony2表单实体更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我Symfony2表单实体更新的特定示例吗?本书仅显示如何创建新实体.我需要一个如何更新现有实体的示例,在该实例中,我最初在查询字符串上传递了该实体的ID.

Can anyone please show me a specific example of a Symfony2 form entity update? The book only shows how to create a new entity. I need an example of how to update an existing entity where I initially pass the id of the entity on the query string.

我在理解如何在不重新创建表单的情况下检查帖子的代码中再次访问表单时遇到了麻烦.

I'm having trouble understanding how to access the form again in the code that checks for a post without re-creating the form.

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

And if I do recreate the form, it means I have to also query for the entity again, which doesn't seem to make much sense.

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

Here is what I currently have but it doesn't work because it overwrites the entity when the form gets posted.

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

推荐答案

正在工作.必须进行一些调整:

Working now. Had to tweak a few things:

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

这篇关于Symfony2表单实体更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆