I have a list of Schools displayed in my list.html.twig. For each school I need to insert some data which is filled in a form inside a modal. I need that once the form is filled, the modal is submitted and closes, showing again the background page. Normally the submit action of the modal causes page refresh, and I want to avoid that obviously.
The inspiration for the code was this tutorial, specifically I followed the creation of the form...
//school controller
$school = new School();
$form = $this->createForm(
new SchoolFormType($param),
$school,
array(
'action' => $this->generateUrl("school_modal_vp", array(
'param' => $param,
)),
'method' => 'POST'
));
if($request->isMethod('POST')) {
$form->handleRequest($request);
if($form->isValid()) {
$data = $form->getData();
$em->persist($data);
$em->flush();
$response = new Response(json_encode([
'success' => true,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
... and the function which "replaces" the submit action of the modal with a AJAX call with form data, storing it to database and closing modal.
<script>
var param_id = '{{ param.id }}';
function sendForm(form, callback) {
// Get all form values
var values = {};
$.each( form[0].elements, function(i, field) {
if (field.type != 'checkbox' || (field.type == 'checkbox' && field.checked)) {
values[field.name] = field.value;
}
});
// Post form
console.log(values);
$.ajax({
type : form.attr( 'method' ),
url : form.attr( 'action' ),
data : values,
success : function(result) { callback( result ); }
});
}
$(function() {
$("#school_"+param_id+"_save").on("click", function( e ) {
e.preventDefault();
sendForm($("#myModalSchool_" + param_id).find('form'), function (response) {
$("#myModalSchool_" + param_id).modal('hide');
});
});
});
</script>
However, this works only for the last modal created while listing the schools. Any help is appreciated, and please if you need ask for details.
EDIT 1:
This is the template as requested
<div class="modal fade" data-backdrop="static" id="myModalSchool_{{ param.id }}">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title">
School
</h3>
</div>
<div class="modal-body">
<form id="school_{{ param.id }}" name="school_{{ param.id }}" method="post" action="{{ path('school_modal_vp', {param_id: param.id, }) }}" class="form-horizontal">
{{ form_errors(form) }}
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
</div>
</div>