I get "The CSRF token is invalid. Please try to resubmit the form" in the registration form

47 Views Asked by At

I have twig form with form_start and form_row functions. I want to customize it, like class names and input types, but I was not able to find a good documentation for that. That is why I moved from those twig functions to html. I have changed only the token's value field. But when I submit the form I get this error The CSRF token is invalid. Please try to resubmit the form.. I guess {{ csrf_token('authenticate') }} is wrong but I was not able to find what should I use for {{ csrf_token('authenticate') }}.

{{ form_start(registrationForm) }}
    {{ form_row(registrationForm.email) }}
    {{ form_row(registrationForm.plainPassword, {
        label: 'Password'
    }) }}

    <button type="submit" class="btn btn-primary">Register</button>
{{ form_end(registrationForm) }}
<form name="registration_form" method="post">
    <div><label for="registration_form_email" class="required">Email</label><input type="text" id="registration_form_email" name="registration_form[email]" required="required" maxlength="180"></div>
    <div><label for="registration_form_plainPassword" class="required">Password</label><input type="password" id="registration_form_plainPassword" name="registration_form[plainPassword]" required="required" autocomplete="new-password"></div>

    <button type="submit" class="btn btn-primary">Register</button>
<input type="hidden" id="registration_form__token" name="registration_form[_token]" value="{{ csrf_token('authenticate') }}"></form>
1

There are 1 best solutions below

0
Simon On

It is really best practice to stick with the twig templating for form tags ! That way your CSRF field will be rendered automatically !

To add a class name to an input you can do so like this :

{{ form_widget(form.task, {'attr': {'class': 'task_field'}}) }}

I took this from this great Symfony doc : https://symfony.com/doc/current/form/form_customization.html