1

I am trying to update the data in my database but unfortunately Symfony keeps creating new data for me. I have the following controller:

public function updateAction(Request $request,$id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('AcmeStoreBundle:Product')->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    $form = $this->createForm(new ProductType(), $product);

    if($request->isMethod('POST')) {
        $form->bind($request);
        if($form->isValid()) {
            $em->persist($product);
            $em->flush();
            $this->get('session')->getFlashBag()->add('green', 'Product Updated!');
        } else {
            //$this->get('logger')->info('This will be written in logs');
            $this->get('session')->getFlashBag()->add('red', 'Update of Product Failed!');
        }
        return $this->redirect($this->generateUrl('acme_store_product_all'));
    }

    return $this->render('AcmeStoreBundle:Default:update.html.twig',array(
        'name' => $product->getName(),
        'updateForm' => $form->createView(),
    ));
}

I just wondering what I am doing wrong. I new to Symfony

EDIT

// Acme/StoreBundle/Form/Type/ProductType.php
namespace Acme\StoreBundle\Form\Type;

use Acme\StoreBundle\Entity\Category;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
        $builder->add('price');
        $builder->add('description');
        $builder->add('category', 'entity',array('class' => 'AcmeStoreBundle:Category',));
    }

    public function getName()
    {
        return 'name';
    }
}
4

1 回答 1

3

您的控制器中的代码是正确的(即使您可以$em->persist($product)从代码中删除,因为实体已经由实体管理器管理)。

我强烈怀疑错误出在您的树枝模板中,并且您的表单未指向控制器中的正确操作:我感觉您已将表单提交给该newAction方法:

<form action="{{ path('product_new') }}" method="post" {{ form_enctype(form) }}>
{# .... #}
</form>

而表单应该指向您updateAction的控制器的方法:

<form action="{{ path('product_update') }}" method="post" {{ form_enctype(form) }}>
{# .... #}
</form>

好吧,这是一个常见的错误:)

于 2013-04-22T06:33:31.790 回答