L.S L.S - 1 year ago 115
PHP Question

symfony ajax form dynamically modify

I have the following form that contains data from the database it still WIP ( i'm missing a few fields that i didn't add yet).
The form loads data in the first select and based on that select i use ajax to populate a second select with options based on the first select ( basically the associations to the selected value). And from there again another select with certain options and so on and at the end when i submit the form i want to generate a report from database based on the data.
For the moment i'm stuck with the second field because i always get an error:

This value is not valid.

The form class:

* @param FormBuilderInterface $builder
* @param array $options
public function buildForm(FormBuilderInterface $builder, array $options)
->add('survey', EntityType::class, [
'class' => SurveyManager::class,
'placeholder' => 'Choose option',
'attr' => [
'class' => 'field-change',
->add('headquarter', ChoiceType::class, [
'choices' => [],
->add('submit', SubmitType::class, [
'label' => 'Save',

I'm not reall sure how to fix the error or how should i handle this type of form. Can you help me out guys ?

Based on the answer i did this

function (FormEvent $event) {
$form = $event->getForm();

$data = $event->getData();

$form->add('headquarter', EntityType::class, [
'class' => HeadQuarterManager::class,
'query_builder' => function(HeadQuarterManagerRepository $er) {

return $er->getHeadquarter($data['survey']);

But i'm getting this error:

Notice: Undefined variable: data

Not really sure how to pass the data to the getHeadquarter method so i can return an array of id => name for the select.

Answer Source

When you run the function $form->isValid(), it checks against the form it built in the buildForm function. Any extra fields/value that aren't there will cause this error.

You can change this behaviour by using form events.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download