簡體   English   中英

Symfony:一頁上有多種形式

[英]Symfony: Multiple forms on one page

我陷入了以下問題。 我在一頁上有3個表單(將來可能會更多)。 當我提交它們時..什么都沒有發生(將數據插入到DB中),而其他2種形式則填寫了它們的字段。可能是因為它們都有一個“名稱”字段嗎? 我該如何解決..這樣每個表單都有自己的“功能”,並且不會干擾其他表單。

我的樹枝:

<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
    }
}

我想,你不需要把他們都在同一個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(),
    ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM