表单 – Symfony2表单实体更新

前端之家收集整理的这篇文章主要介绍了表单 – Symfony2表单实体更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
得到它的工作请参阅以下更新:

任何人都可以向我展示一个Symfony2表单实体更新的具体例子?本书仅显示如何创建一个新实体。我需要一个例子,说明如何更新现有的实体,我最初在查询字符串上传递实体的id。这是我目前拥有的,但它不起作用,因为它覆盖实体的表单发布。我想我在理解中遇到的问题是如何在不重新创建表单的情况下在检查帖子的代码中再次访问表单。如果我重新创建表单,这意味着我也必须再次查询该实体,这似乎没有什么意义。

  1. public function updateAction($id)
  2. {
  3. $em = $this->getDoctrine()->getEntityManager();
  4. $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
  5. $form = $this->createForm(new TestimonialType(),$testimonial);
  6.  
  7. $request = $this->get('request');
  8. if ($request->getMethod() == 'POST') {
  9. $form->bindRequest($request);
  10.  
  11. echo $testimonial->getName();
  12.  
  13. if ($form->isValid()) {
  14. // perform some action,such as save the object to the database
  15. //$testimonial = $form->getData();
  16. echo 'testimonial: ';
  17. echo var_dump($testimonial);
  18. $em->persist($testimonial);
  19. $em->flush();
  20.  
  21. return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));
  22. }
  23. }
  24.  
  25. return $this->render('MyBundle:Testimonial:update.html.twig',array(
  26. 'form' => $form->createView()
  27. ));
  28. }

更新:现在工作。不得不调整几点:

  1. public function updateAction($id)
  2. {
  3. $request = $this->get('request');
  4.  
  5. if (is_null($id)) {
  6. $postData = $request->get('testimonial');
  7. $id = $postData['id'];
  8. }
  9.  
  10. $em = $this->getDoctrine()->getEntityManager();
  11. $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
  12. $form = $this->createForm(new TestimonialType(),$testimonial);
  13.  
  14. if ($request->getMethod() == 'POST') {
  15. $form->bindRequest($request);
  16.  
  17. if ($form->isValid()) {
  18. // perform some action,such as save the object to the database
  19. $em->flush();
  20.  
  21. return $this->redirect($this->generateUrl('MyBundle_list_testimonials'));
  22. }
  23. }
  24.  
  25. return $this->render('MyBundle:Testimonial:update.html.twig',array(
  26. 'form' => $form->createView()
  27. ));
  28. }

解决方法

现在工作不得不调整几点:
  1. public function updateAction($id)
  2. {
  3. $request = $this->get('request');
  4.  
  5. if (is_null($id)) {
  6. $postData = $request->get('testimonial');
  7. $id = $postData['id'];
  8. }
  9.  
  10. $em = $this->getDoctrine()->getEntityManager();
  11. $testimonial = $em->getRepository('MyBundle:Testimonial')->find($id);
  12. $form = $this->createForm(new TestimonialType(),array(
  13. 'form' => $form->createView()
  14. ));
  15. }

猜你在找的HTML相关文章