[英]Symfony 2 - add options into 'Choice' field after form is created
創建字段后,我們可以編輯選項字段的可能選項嗎?
假設,選擇字段(類別的下拉框)的可能選項來自我的數據庫。 我的控制器如下所示:
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())
);
}
您需要使用EventSubscriber,在此處檢查文檔: http : //symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-underlying-data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.