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