Symfony:一页上有多个表单

时间:2017-05-26 14:43:44

标签: php forms symfony

我遇到了以下问题。我在一个页面上有3个表单(未来可能会更多)。当我提交它们时......没有任何反应(在数据库中插入数据),而其他两个表格填写了它们的字段。可能因为它们都有一个“名称”字段?我怎样才能解决这个问题......所以每个表格都有自己的“功能”,并且不会干扰其他形式。

我的树枝:

<div class="box">
            <h2>Form1</h2>
            {{ form_start(form1) }}
            {{ form_widget(form1) }}
            {{ form_end(form1) }}
        </div>
        <div class="box">
            <h2>Form2</h2>
            {{ form_start(form2) }}
            {{ form_widget(form2) }}
            {{ form_end(form2) }}
        </div>
        <div class="box">
            <h2>Form3</h2>
            {{ form_start(form3) }}
            {{ form_widget(form3) }}
            {{ form_end(form3) }}
        </div>

我的控制器:

if ($request->isMethod('POST')) {

    $form1->handleRequest($request);
    $form2->handleRequest($request);
    $form3->handleRequest($request);

    if ($form1->isSubmitted() && $form1->isValid() && $request->request->has('form1')) {
        // Do data insert

        //Return to page
    } else if ($form2->isSubmitted() && $form2->isValid() && $request->request->has('form2')) {
        // Do data insert

        //Return to page
    } else if ($form3->isSubmitted() && $form3->isValid() && $request->request->has('form2')) {
        // Do data insert

        //Return to page
    }
}

1 个答案:

答案 0 :(得分:2)

我认为你不需要将它们全部放在同一个if中。你能做的就是将它们分开:

public function whateverAction(Request $request) {
    $form1 = $this->createForm(...);
    $form2 = $this->createForm(...);
    $form3 = $this->createForm(...);

    $form1->handleRequest($request);
    if ($form1->isSubmitted() && $form1->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($obj1); //of whatever the entity object you're using to create the form1 form
        $em->flush();
    }

    $form2->handleRequest($request);
    if ($form2->isSubmitted() && $form2->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($obj2); //of whatever the entity object you're using to create the form2 form
        $em->flush();
    }

    $form3->handleRequest($request);
    if ($form3->isSubmitted() && $form3->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($obj3); //of whatever the entity object you're using to create the form3 form
        $em->flush();
    }

    return $this->render('...', [
        'form1'=>$form1->createView(),
        'form2'=>$form2->createView(),
        'form3'=>$form3->createView(),
    ]);
}