簡體   English   中英

Symfony 2-在創建表單后將選項添加到“選擇”字段中

[英]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())
    );      
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM