Symfony2 prevent multiple form submission

csrf, forms, submit, symfony

Solution

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.

Problem

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 : - User fills the form and clicks on the submit button (form is then posted) - User quickly press the escape key - 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!

Original source

Related problems