Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 prevent multiple form submission

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 :

  1. User fills the form and clicks on the submit button (form is then posted)
  2. User quickly press the escape key
  3. User clicks again on the submit button (form is posted again)

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!

like image 238
Bil5 Avatar asked Dec 11 '22 04:12

Bil5


1 Answers

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.

like image 97
baris1892 Avatar answered Dec 20 '22 15:12

baris1892