Symfony编辑表单不起作用

时间:2017-07-15 20:39:31

标签: php forms symfony submit edit

我想用symfony表单编辑我的数据,我有一个问题 可能与我的控制器。我有一些这样的:

  public function detailAction($id,Request $request)
{
    $order = $this->getDoctrine()->getRepository(OrderMain::class)->find($id);

    if (!$order) {
        throw $this->notFoundException();
    }

    $form = $this->createForm(OrderMainType::class, $order);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
//            do not enter here
            $orderEdit = $form-getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($orderEdit);
            $em->flush();
        }

    return $this->render('ModiModiAdminBundle:Order:detail.html.twig',array(
        'form' => $form->createView(),
        ));
}


 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
   /.../
 ->add('edit', SubmitType::class, array(
                                  'attr' =>array('class'=>'edit'),
            ));
    }

所有显示corectly但当我点击一个按钮我的页面重新加载(不保存更改)。感谢帮助。

2 个答案:

答案 0 :(得分:0)

这是您的控制器方法的问题。下面应该适合你。

public function detailAction($id,Request $request)
{
    $order = $this->getDoctrine()->getRepository(OrderMain::class)->find($id);

    if (!$order) {
        throw $this->notFoundException();
    }

    $form = $this->createForm(OrderMainType::class, $order);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
            //do not enter here
            $em = $this->getDoctrine()->getManager();
            $em->flush();
        }

    return $this->render('ModiModiAdminBundle:Order:detail.html.twig',array(
        'form' => $form->createView(),
        ));
}

您可以删除$orderEdit = $form-getData();行。提交表单后,应根据提交的数据更新实体。由于这已经是托管实体,您还可以删除$em->persist($orderEdit);

答案 1 :(得分:0)

public function edit(Request $request)
{
 $id = $request->get('id');
 $category = $this->getDoctrine()->getRepository(Category::class)->find($id);

    if (!$category) {
        throw $this->notFoundException();
    }
    $form = $this->createForm(CategoryType::class,$category);
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()){
        $em = $this->getDoctrine()->getManager();
        $categoryData = $form->getData();
        $em->persist($categoryData);
        $em->flush();
    }

    return $this->render('admin/category/edit.html.twig',array(
        'form' => $form->createView(),
    ));
}

您丢失=>处理来自代码的请求 $ form-> handleRequest($ request);