Raph Raph - 2 years ago 94
PHP Question

Add form fields based on form choice

I need to dynamically add fields to a form based on user input. Let's suppose that I have an entity A with subentities B and C. Initially the form has a choice field where the user can select the type, B or C. If the user select B the fields B.x and B.y should be added to the form, and if the user select C the fields C.x, C.y and C.z should be added instead.

Can I do this using PHP/Symfony, or do I need to use JavaScript to show/hide fields? I was reading the Dynamic Form Modification tutorial on Symfony but I still couldn't figure out how to do this.

Answer Source

The easiest solution will be to split the form up in two pages. The first page displays only parts of the form that don't depend on any user selection. The user submits the form and is then presented with a second form that contains form fields based on the input of the first form.

You just define a form type for the first page and then for all possible outcomes of the second page. You can also use the dynamic form modification you already read about if this makes more sense than creating completely different forms. Then, in the controller, you add your logic to decide which form to present.

Maybe it would look something like this:

$entity = new Entity();
$form1 = $this->createForm(new EntityPageOneType(), $entity);
if($form1->isSubmitted() && $form1->isValid()){
    if($entity->foo = 'bar'){
        $form2 = $this->createForm(new EntityPageTwoBarType(), $entity);
        $form2 = $this->createForm(new EntityPageTwoOtherType(), $entity);
    if($form2->isSubmitted() && $form2->isValid()){
         // persist data & redirect
    return $this->render('template.twig', ['form' => $form2]);
    return $this->render('template.twig', ['form' => $form1]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download