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

这行得通。$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())
    );      
}
4

1 回答 1

0

您需要使用 EventSubscriber,查看文档,这里:http ://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-underlying-data

于 2013-10-28T19:02:13.583 回答