得到它的工作请参阅以下更新:
任何人都可以向我展示一个Symfony2表单实体更新的具体例子?本书仅显示如何创建一个新实体。我需要一个例子,说明如何更新现有的实体,我最初在查询字符串上传递实体的id。这是我目前拥有的,但它不起作用,因为它覆盖实体的表单发布。我想我在理解中遇到的问题是如何在不重新创建表单的情况下在检查帖子的代码中再次访问表单。如果我重新创建表单,这意味着我也必须再次查询该实体,这似乎没有什么意义。
public function updateAction($id) { $em = $this->getDoctrine()->getEntityManager(); $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id); $form = $this->createForm(new TestimonialType(),$testimonial); $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->bindRequest($request); echo $testimonial->getName(); if ($form->isValid()) { // perform some action,such as save the object to the database //$testimonial = $form->getData(); echo 'testimonial: '; echo var_dump($testimonial); $em->persist($testimonial); $em->flush(); return $this->redirect($this->generateUrl('MyBundle_list_testimonials')); } } return $this->render('MyBundle:Testimonial:update.html.twig',array( 'form' => $form->createView() )); }
更新:现在工作。不得不调整几点:
public function updateAction($id) { $request = $this->get('request'); if (is_null($id)) { $postData = $request->get('testimonial'); $id = $postData['id']; } $em = $this->getDoctrine()->getEntityManager(); $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id); $form = $this->createForm(new TestimonialType(),$testimonial); if ($request->getMethod() == 'POST') { $form->bindRequest($request); if ($form->isValid()) { // perform some action,such as save the object to the database $em->flush(); return $this->redirect($this->generateUrl('MyBundle_list_testimonials')); } } return $this->render('MyBundle:Testimonial:update.html.twig',array( 'form' => $form->createView() )); }
解决方法
现在工作不得不调整几点:
public function updateAction($id) { $request = $this->get('request'); if (is_null($id)) { $postData = $request->get('testimonial'); $id = $postData['id']; } $em = $this->getDoctrine()->getEntityManager(); $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id); $form = $this->createForm(new TestimonialType(),array( 'form' => $form->createView() )); }