2013-10-28 41 views
1

字段創建後,我們可以編輯選擇字段的可能選項嗎?Symfony 2 - 創建表單後在「選擇」字段中添加選項

比方說,選擇字段(類別的下拉框)的可能選項來自我的數據庫。我的控制器看起來是這樣的:

public function addAction(Request $request){ 
    //get the form 
      $categories = $this->service->getDataFromDatabase(); 
    $form = $this->formFactory->create(new CategoryType(), $categories); 

    $form->handleRequest($request); 
    if ($form->isValid()) { 
     // perform some action, such as saving the task to the database, redirect 

    } 

    return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig', 
     array('form' => $form->createView()) 
    );  
} 

This works。 $類別被填充爲下拉框,以便用戶可以選擇一個類別。我不喜歡這段代碼的是,當用戶點擊提交併且表單驗證輸入時,它必須再次點擊「getDataFromDatabase」服務。這對我來說是沒有必要的。理想情況下,只有在驗證失敗時才需要訪問服務,並且必須爲用戶重新生成表單。我希望使控制器是這個樣子:

public function addAction(Request $request){ 
    //get the form 
    $form = $this->formFactory->create(new CategoryType()); 

    $form->handleRequest($request); 
    if ($form->isValid()) { 
     // perform some action, such as saving the task to the database, redirect 

    } 

      $categories = $this->service->getDataFromDatabase(); 
      $form->setData($categories); //this tells the choice field to use $categories to populate the options 

    return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig', 
     array('form' => $form->createView()) 
    );  
} 

回答

0
+0

謝謝你的提示Djuro。我做了一個自定義表單事件,在數據驗證後觸發。成功了! – dyip1

+0

哪個FormEvents常量和您使用哪種FormInterface方法添加選項? –

+0

我認爲這是PRE_SUBMIT和方法preSubmit。我不記得這些東西。無論如何,我使用Kint調試器,因此我可以在整個過程的任何時刻轉儲並檢查$ event-> getData()實際包含的內容。 –

相關問題