简体   繁体   中英

Symfony2 updating data with a form

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';
    }
}

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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