Symfony 2 - 在创建表单后将选项添加到“选择”字段中

时间:2013-10-28 18:15:56

标签: php forms symfony twig

我们可以在创建字段后编辑选项字段的可能选项吗?

让我们说,选择字段的可能选项(类别的下拉框)来自我的数据库。我的控制器看起来像这样:

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

1 个答案:

答案 0 :(得分:0)