2013-04-21 87 views
0

我试图更新数据库中的数据,但不幸的是Symfony不断为我创建新数据。我有以下控制器:Symfony2使用表格更新数据

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

我只是想知道我做错了。我新来的Symfony

编辑

// 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'; 
    } 
} 
+0

不知道,但如果不是像你那样使用'$ request',而是使用'$ this-> getRequest()'?当你调用'$ this-> render()'时,你不需要发送'$ product-> getName()'。 (你的对象'$ form'已经知道你的对象'$ product') – cheesemacfly 2013-04-22 04:37:00

+1

你需要发布'ProductType'来解决这个问题。这很可能会抹掉主键(通常是'id')。 – Alex 2013-04-22 05:20:04

+0

我用'ProductType.php' – Sevenearths 2013-04-22 08:23:54

回答

2

在你的控制器中的代码是正确的(即使你可以从你的代码中删除$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> 

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

+0

Spot更新了我的问题。经典newbee错误 – Sevenearths 2013-04-22 08:31:12