Reputation: 5371
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';
}
}
Upvotes: 1
Views: 3547
Reputation: 31919
The code in your controller is correct (even though you can remove $em->persist($product)
from your code as the entity is already managed by the entity manager).
I strongly suspect the error is in your twig template and that your form does not point to the right action in your controller:
I have a feeling you have the form submitted to the newAction
method:
<form action="{{ path('product_new') }}" method="post" {{ form_enctype(form) }}>
{# .... #}
</form>
whereas the form should instead point to your updateAction
method of your controller:
<form action="{{ path('product_update') }}" method="post" {{ form_enctype(form) }}>
{# .... #}
</form>
Well, that's a common mistake :)
Upvotes: 3