Symfony 4 - how to add csrf token without building form?

{{ form_end() }} works only if you have something like this:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

You can create custom token in your controller and then pass it to the view like this:

    $csrf = $this->container->get('security.csrf.token_manager');
    $token = $csrf->refreshToken('yourkey');

And then create hidden input in your twig with token:

<input type="hidden" name="_token" value="{{ token }}">

You can use the helper twig function csrf_token as described in the doc here, as example:

 <input type="hidden" name="_csrf_token"
        value="{{ csrf_token('authenticate') }}"
    >

More help in this answer.

UPDATE:

Other strategy: pass from controller:

    $tokenProvider = $this->container->get('security.csrf.token_manager');
    $token = $tokenProvider->getToken('example')->getValue();

Hope this help


You can use {{ form_row(form._token) }} to generate the required CSRF token field to your form render in Symfony 3 (i'm currenlty use this method with Symfony 3.4).