我们可以在创建字段后编辑选项字段的可能选项吗?
让我们说,选择字段的可能选项(类别的下拉框)来自我的数据库。我的控制器看起来像这样:
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())
);
}
这很有效。 $ categories被填充为下拉框,因此用户可以选择一个类别。我不喜欢这段代码的是,当用户点击提交并且表单验证输入时,它必须再次点击“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)
您需要使用EventSubscriber,查看文档,在这里:http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-underlying-data