自定义Twig表单转HTML后出现CSRF令牌无效问题求助
自定义HTML表单替代Twig组件后CSRF令牌无效的解决方法
原本用Twig的form_start和form_row渲染注册表单,因为需要自定义类名、输入类型,改成纯HTML实现后,仅修改了令牌的value字段,提交时出现错误:
The CSRF token is invalid. Please try to resubmit the form.
问题出在你使用的{{ csrf_token('authenticate') }}——这个是登录表单的CSRF令牌ID,和注册表单的令牌不匹配。下面给出两种解决办法:
原Twig代码
{{ 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) }}
改写后的原HTML代码
<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:直接从表单对象获取令牌值(最稳妥)
不用自己调用csrf_token函数,直接用Twig表单对象里的令牌值替换:
<input type="hidden" id="registration_form__token" name="registration_form[_token]" value="{{ registrationForm._token.vars.value }}">
这样生成的令牌和原Twig表单渲染的完全一致,不会出错。
解决方法2:使用注册表单对应的CSRF令牌ID
如果要继续用csrf_token函数,需要传入注册表单对应的令牌ID:
- 这个ID通常是表单的名称(比如
registration_form),或者查看你的表单类中configureOptions方法里设置的csrf_token_id值。 - 假设表单类里设置的是
registration_form,则修改为:
<input type="hidden" id="registration_form__token" name="registration_form[_token]" value="{{ csrf_token('registration_form') }}">
额外建议:不用完全放弃Twig表单组件
其实Twig表单支持自定义类名、输入类型,不用全写HTML。比如给字段加自定义类和修改输入类型:
{{ form_row(registrationForm.email, { 'attr': {'class': 'your-custom-class', 'type': 'email'} }) }} {{ form_row(registrationForm.plainPassword, { label: 'Password', 'attr': {'class': 'password-input', 'autocomplete': 'new-password'} }) }}
这样既能利用Twig表单的自动渲染,又能满足自定义需求,还能避免手动写HTML时的令牌、字段名等错误。
内容的提问来源于stack exchange,提问作者ilhan
相关产品推荐
相关产品推荐

