I'm working on a a form with Symfony2. I have some entity fields and a csrf token that is correctly rendered thanks to {{ form_rest(myform) }}
.
The problem is :
Result: an entity (form is binded to an entity) is inserted twice in the database
And that can occur infinitely
I thought that with the CSRF token field, it would prevent this situation but that's not the case. So is there any way to figure it out natively with Symfony framework? If not what possibilities exist?
Thank you in advance!
I'm not sure if this is the right approach, but you can do the following.
In your FormType
, set following options:
For Symfony < 4 use intention
:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csrf_protection' => true,
'csrf_field_name' => '_token',
// important part; unique key
'intention' => 'form_intention',
]);
}
For Symfony >= 4 use csrf_token_id
:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csrf_protection' => true,
'csrf_field_name' => '_token',
// important part; unique key
'csrf_token_id' => 'form_intention',
]);
}
Then in your controller action you can do something like this using your intention
or csrf_token_id
:
if ($form->isSubmitted()) {
// refresh CSRF token (form_intention)
$this->get("security.csrf.token_manager")->refreshToken("form_intention");
}
This prevents the double submission of the given form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With