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';
}
}
不知道,但如果不是像你那样使用'$ request',而是使用'$ this-> getRequest()'?当你调用'$ this-> render()'时,你不需要发送'$ product-> getName()'。 (你的对象'$ form'已经知道你的对象'$ product') – cheesemacfly 2013-04-22 04:37:00
你需要发布'ProductType'来解决这个问题。这很可能会抹掉主键(通常是'id')。 – Alex 2013-04-22 05:20:04
我用'ProductType.php' – Sevenearths 2013-04-22 08:23:54