0

I have a little problem with Symfony2 and Javascript.

I have a form with a select box:

$builder
   ->add('town', 'entity', [
       'class' => 'AppBundle:Towns',
       'property' => 'id',
       'placeholder' => 'Select an item',
       'required' => true,
   ]);

When I click on a town, the taxes associated to the selected town must be displayed in the form, as check boxes.

For what I understand, I must call to a controller via AJAX and get a JSON of the id's and the descriptions of the taxes, isn't it? But then what should I do to add this information to the form? And how can I intercept the "selected" event of this selectbox?

And should I do anything to send the information to the server, when a user click on the "Send" button? AFAIK, Symfony2 has some mechanisms to avoid sending data not generated by the form, isn't it?

mHouses
  • 875
  • 1
  • 16
  • 36
  • Where do you get the information about the taxes from? Haven't you got them stored in your database? – cezar Jun 12 '15 at 09:15
  • @cezar Yes, it's from the database, but each town has different taxes, so I can't load it when I'm creating the form – mHouses Jun 12 '15 at 09:16
  • Do you have a relationship with the taxes and the other table that you create form to save data? As i can understand; towns is not required to save but only for getting taxes data? – Canser Yanbakan Jun 12 '15 at 09:26
  • @R.CanserYanbakan No, I haven't any relationship because this form doesn't create any table. This form is for generating some reports. And yes, the town is only required for choosing which taxes to calculate. – mHouses Jun 12 '15 at 09:30

1 Answers1

1

You have to define a collection field to your form builder.

Just add it like this;

$builder->add('taxes', 'collection', [
    'type' => 'checkbox',
    'options' => ['required' => true] 
];

Call it from your view:

{{ form_row(form.taxes) }} // or just use render all form field with form_widget(form)

And then, you have to write some javascript to add / remove taxes to your collection.

If you want to select taxes based on selected towns, so; make an ajax request to your controller that returns json/html data and then add that to your form like;

<input type="checkbox" name="taxes[]" value="your_tax_value" />
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
  • This works well, but there is a problem: When I receive the response in the controller (after the `$form->handleRequest($request)` and the `$results=$form->getData()`), all I got is an array of values, something like `['id' => true]`. It's possible to get, directly, the checked entities? – mHouses Jun 19 '15 at 07:01
  • Yes it is. Take a look here: http://stackoverflow.com/questions/8987418/how-to-get-form-values-in-symfony2-controller – Canser Yanbakan Jun 22 '15 at 09:50