2013-10-28 42 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()实际包含的内容。 –

相关问题