CSRF 令牌无效.请尝试重新提交表单令牌、表单、请尝试、CSRF

由网友(山雨欲来风满楼)分享简介:每次我尝试提交表单时都会收到此错误消息:I'm getting this error message every time I try to submit the form:CSRF 令牌无效.请尝试重新提交表单The CSRF token is invalid. Please try to resubmit th...

每次我尝试提交表单时都会收到此错误消息:

I'm getting this error message every time I try to submit the form:

CSRF 令牌无效.请尝试重新提交表单

The CSRF token is invalid. Please try to resubmit the form

我的表单代码是这样的:

My form code is this:

<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
    <div class="form-group">
        {{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.email) }}
    </div>

    <div class="form-group">
        {{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        {{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}
    </div>

    <div class="form-group">
        {{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        <div class="col-md-1 control-label">
        <input type="submit" value="submit">
    </div>

    </div>
</form>

有什么想法吗?

推荐答案

您需要在表单中添加 _token

You need to add the _token in your form i.e

{{ form_row(form._token) }}

到目前为止,您的表单缺少 CSRF 令牌字段.如果您使用 twig 表单函数来呈现您的表单,例如 form(form) 这将自动为您呈现 CSRF 令牌字段,但您的代码显示您正在使用原始 HTML 呈现您的表单,例如 <form></form>,所以你必须手动渲染字段.

As of now your form is missing the CSRF token field. If you use the twig form functions to render your form like form(form) this will automatically render the CSRF token field for you, but your code shows you are rendering your form with raw HTML like <form></form>, so you have to manually render the field.

或者,只需在表单的结束标记之前添加 {{ form_rest(form) }}.

Or, simply add {{ form_rest(form) }} before the closing tag of the form.

根据文档

这会渲染给定的所有尚未渲染的字段形式.始终将其放在表单中的某个地方是个好主意因为它会为您呈现隐藏字段并制作您忘记的任何字段渲染得更明显(因为它会为您渲染该字段).

This renders all fields that have not yet been rendered for the given form. It's a good idea to always have this somewhere inside your form as it'll render hidden fields for you and make any fields you forgot to render more obvious (since it'll render the field for you).

form_rest(view, variables)

阅读全文

相关推荐

最新文章