I have used this answer to create a form for a list of entities with a checkbox on each row:
Form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('sites', EntityType::class, [
'required' => false,
'class' => Site::class,
'choice_label' => function($site){
return '['.$site->getId().']';
},
'multiple' => true,
'expanded' => true
]);
}
Twig:
{% for site in sites %}
<tr>
<td>{{ form_widget(actionform.sites[site.getId]) }}</td>
However I can't get submitting the ajax right:
Currently I'm using:
$.post(
'{{ path('site_add_to_upgrade', { 'page': page } ) }}',
{
'site_action_form[_token]': '{{ actionform._token.vars.value }}',
'site_action_form[sites]': $('.itemlist input[name^="site_action_form"]:checked').serialize()
}
)
but this throws an the Error:
\Symfony\component\Form\FormError
message: This value is not valid
messageParameters:
{{ value }}: site_action_form%5Bsites%5D%5B%5D=4
How can I submit these checkboxes, so I can loop through them?
I would divide the work in two parts : 1 - Make sure the form works when sending it in sync. 2 - Send your form as is using ajax :
$(this).on('submit', '#wrapper_id > form', function(event){
event.preventDefault();
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data, function(data) {
//process with return data
});
});
For the records, this is more an jQuery question than a symfony, or ajax one.
Hope this helps