2017-08-15 43 views
0

我在使用while循環在Symfony中循環表格時遇到了問題。當用戶進入一個學期並且與註冊相匹配時,重申表格,讓他們進入第二學期,然後進入第三學期。我沒有正確地做,或者我可以重申entity = new Student();讓他們進入兩個實體。如何在Symfony中循環表格/新實體

public function createAction(Request $request){ 
    $entity = new Student(); 
    $form = $this->createCreateForm($entity); 
    $form->handleRequest($request); 

    if ($form->isSubmitted() && $form->isValid()) { 
     $em = $this->getDoctrine()->getManager(); 
     $student = $em->getRepository('AcmeDemoBundle:Payrollperiod') 
        ->findOneBy([ 
         'begindate'=>$form->get('beginDate')->getData(), 
         'lastdate'=>$form->get('lastDate')->getData() 
        ]); 

     $registration = $em->getRepository('AcmeDemoBundle:Payrollweek') 
        ->findBystartdateAndenddate(
         $form->get('beginDate')->getData(), 
         $form->get('lastDate')->getData() 
        ); 

     $counter = count($registration); 

     while($counter<=2) { 
      if ($student){ 
        $this->addFlash('error', 'Duplicate error: Student Period already existed.'); 
        return $this->redirect($this->generateUrl('student')); 
      } 
      elseif ($registration){ 
       foreach ($registration as $reg) { 
        $reg->setStudentid($entity); 
       } 
       $em->persist($entity); 
       $em->flush(); 

       return $this->redirect($this->generateUrl('payrollperiod')); 
      } 
      else{ 
       $this->addFlash('error', ' does not match .'); 
       return $this->redirect($this->generateUrl('student')); 
      } 
     } 

     return array(
      'entity' => $entity, 
      'form' => $form->createView(), 
     ); 

    } 
} 
+0

我在設計中看到了一些問題,我不認爲它會按照您的預期進行操作。 –

+0

同意。這不是網絡請求的工作方式 –

回答

0

閱讀文檔http://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields添加字段。當用戶需要添加第二個或更多時段時,您的UI /前端應創建更多字段。我應該生成適當的Symfony表單元素,然後當您發佈時,可以像處理標準表單文章一樣處理它,迭代請求,因爲這些時間段將作爲數組提交。

我在過去做過這樣的事情,我添加一個新的表單行是一個AJAX調用模板,該模板描述了表單輸入字段,所以我不必在Javascript/jQuery中創建表單HTML。 .append()將模板結果發送到表單並處理請求。