Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Forms - how to use dynamic select options

I'm working on a form that is being used for sending notifications. In the form I have, among other fields, one input file field. In this field I'm loading a CSV file. From the CSV (contains a column of emails) I'm extracting the data using https://code.google.com/p/jquery-csv/ and add it to a select readonly multiple field with all options selected.

Note: I've created the form using Form Types (by the Symfony2 book) - class NotificationType extends AbstractType; The form is submitted through AJAX;

1. Strike one Taking into account that the select field is being populated dynamically, I've decided not to add it to the form builder but to inject it using JavaScript.

It was a bad move, because when submitting the form, Symfony2 validates that the fields added in the form builder are the exact ones that are submitted. The error returned is: This form should not contain extra fields.

2. Strike two Moving on from strike one I wanted to see if I can work around that, so I added the select field in the form builder but without options, also injecting the options via JavaScript.

Still no luck. Symfony2 also makes sure you can't submit an option that was not added to the form builder when adding the field. The error returned is: This value is not valid.

3. Strike three From Strike 1 and 2, I'm guessing that the only way to make this work would be to add all possible options in the form builder in the choices array when adding the field. This way the field and options would be valid for submit.

But this is not something I would consider a viable option, especially because in the select field I'm expecting 10000 possible results which I'm not aware of until I'm loading the CSV file.

Can you suggest any other approach for this one?

Thanks!

like image 814
Radu Avatar asked Sep 29 '22 01:09

Radu


1 Answers

Take a look at how to dynamically modify forms (example #3).

You'll need to do this as the the form will validate against the builder options, so if you add a new field or change its options when rendered it won't know about it.

Or you don't map the form to a model/entity and process it yourself.

like image 90
Rooneyl Avatar answered Oct 11 '22 16:10

Rooneyl