简体   繁体   中英

Symfony 2 - add options into 'Choice' field after form is created

Can we edit the possible options for a choice field after the field has been created?

Let's say, the possible options for the choice field(a drop down box for categories) comes from my database. My controller would look like this:

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

This works. $categories is populated as a dropdown box so the user can select a category. What I don't like about this code is that it has to hit the "getDataFromDatabase" service again when the user hits submit and the form validates the input. This feels unnecessary to me; ideally it should only need to hit the service when validation fails and the form has to be regenerated for the user. I'm hoping to make the controller look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM