amine amine - 3 months ago 16
Twig Question

Symfony2 Error : The CSRF token is invalid. Please try to resubmit the form

I've been trying to submit a form which update a Cliente object in modal.
When I try to do it this error message showing:
The CSRF token is invalid. Please try to resubmit the form.

her is my Controller :

public function editClienteAction(Request $req,$id)
{
$c=$this->getDoctrine()->getRepository("MFCBClienteBundle:Cliente")->find($id);
$form=$this->createFormBuilder($c)
->add('nom','text')
->add('prenom','text')
->add('age','text')
->add('adresse','text')
->add('tel','text')
->add('email','text')
->add('save','submit')
->getForm();
if ($this->getRequest()->getMethod() == 'POST') {
$form->handleRequest($req);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($c);
$em->flush();

$response = new Response(json_encode([
'success' => true,
]));

$response->headers->set('Content-Type', 'application/json');
return $response;

}
}
return $this->render('MFCBClienteBundle:Default:editCliente.html.twig', array('id'=>$id,'form' => $form->createView()));

}


template editCliente

<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">&times;</span>
</button>
<h4 class="modal-title" id="editModalLabel">Modifier cliente</h4>
</div>
<div class="modal-body">
{{ form_start(form, {'attr': {'class': 'form-horizontal','id':'editForm'}}) }}
{# Les erreurs générales du formulaire. #}
{{ form_errors(form) }}
<div class="form-group">
{# Génération du label. #}
{{ form_label(form.nom, "Nom : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{# Affichage des erreurs pour ce champ précis. #}
{{ form_errors(form.nom) }}
<div class="col-sm-4">
{# Génération de l'input. #}
{{ form_widget(form.nom, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

<div class="form-group">
{{ form_label(form.prenom, "Prénom : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{{ form_errors(form.prenom) }}
<div class="col-sm-4">
{{ form_widget(form.prenom, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

<div class="form-group">
{{ form_label(form.age, "Age : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{{ form_errors(form.age) }}
<div class="col-sm-4">
{{ form_widget(form.age, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

<div class="form-group">
{{ form_label(form.tel, "Tèl : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{{ form_errors(form.tel) }}
<div class="col-sm-4">
{{ form_widget(form.tel, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

<div class="form-group">
{{ form_label(form.adresse, "Adresse : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{{ form_errors(form.adresse) }}
<div class="col-sm-4">
{{ form_widget(form.adresse, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

<div class="form-group">
{{ form_label(form.email, "Email : ", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}
{{ form_errors(form.email) }}
<div class="col-sm-4">
{{ form_widget(form.email, {'attr': {'class': 'form-control'}}) }}
</div>
</div>

</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
{# Pour le bouton, pas de label ni d'erreur, on affiche juste le widget #}
{{ form_widget(form.save, {'attr': {'class': 'btn btn-primary'}}) }}
{# Fermeture de la balise <form> du formulaire HTML #}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>




template index

<table class="table table-striped ">
<thead>
<tr>
<th>Nom</th><th>Prénom</th><th>Age</th><th>Adresse</th><th>Tel</th><th>Email</th><th>Opération</th>
</tr>
</thead>
<tbody>
{%for c in modal.listClientes %}
<tr>
<td>{{ c.nom }}</td><td>{{ c.prenom }}</td><td>{{ c.age }}</td><td>{{ c.adresse }}</td><td>{{ c.tel }}</td><td>{{ c.email }}</td>
<td>
<div class="list-inline">
<a class="editLink btn" href="{{ path('editCliente', {'id': c.id}) }}" >
<i class="glyphicon glyphicon-pencil" aria-hidden="true"></i>&nbsp; Modifier</a>
</div>
</td>
</tr>
{%endfor%}
</tbody>
</table>

<!-- editModal-->
<div id="editModal" class="modal fade edit-modal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">

</div>


JS :

<script>

$(document).ready(function(){

var theHREF;




//EditCliente
$(".editLink").click(function(e) {
e.preventDefault();
theHREF = $(this).attr("href");
$('#editModal').load(theHREF);

$("#editModal").modal("show");

$("#form_save").click(function(e) {
e.preventDefault();

var values = {};
$.each( $("#editForm")[0].elements, function(i, field) {
if (field.type != 'checkbox' || (field.type == 'checkbox' && field.checked)) {
values[field.name] = field.value;
}
});

$.post( theHREF,$("#editForm").serialize() ,function(data) {
if ( data.success === true){
alert("Cliente bien modifier !!");
$("#editModal").modal('hide');
}
else {
$("#editModal").html(data);
}
});
});
});


});

</script>

Answer

Check your html template editClient:

<div class="modal-content">
    {{ form_start(form, ...) }} // right position!
    <div class="modal-body">
        {{ form_start(form, ...) }} // wrong position!
        ...
    </div>
    <div class="modal-footer">
        ...
        {{ form_widget(form.save, ...) }}
    </div>
    {{ form_rest(form) }}  
    {{ form_end(form) }}
</div>

The form_rest and form_end functions must be in the same DOM element container that form_start (i.e. the same level), otherwise the form element is rendered empty in this case.

So, the serialized data form to sent would be empty and the form token required won't sent. Check this inspecting your code on the browser.