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?

4
  • Where do you get the information about the taxes from? Haven't you got them stored in your database? Commented Jun 12, 2015 at 9: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 Commented Jun 12, 2015 at 9: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? Commented Jun 12, 2015 at 9: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. Commented Jun 12, 2015 at 9:30

1 Answer 1

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" />
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Yes it is. Take a look here: stackoverflow.com/questions/8987418/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.