FOS用户捆绑表单(登录,注册,...)工作正常,但不是我自己的表单,给我:
CSRF令牌无效。请尝试重新提交表单
我正在尝试创建一个资源:
http://www.project.local/app_dev.php/developer/new
甚至:
http://www.project.local/developer/new
/Library/WebServer/Documents/project/web
7.1.2
3.2.*
~2.0@dev
^2.0
应用/配置/ config.yml
framework:
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
trusted_hosts: ~
trusted_proxies: ~
session:
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/../var/sessions/%kernel.environment%"
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
form_themes:
- 'form/form_div_layout.html.twig'
应用/配置/ security.yml
security:
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
DeveloperController
public function newAction(Request $request)
{
$developer = new Developer();
$form = $this->createForm(DeveloperType::class, $developer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($developer);
$em->flush($developer);
return $this->redirectToRoute('developer_show', array('id' => $developer->getId()));
}
return $this->render('BackendBundle:Developer:new.html.twig', array(
'developer' => $developer,
'form' => $form->createView(),
));
}
DeveloperType
class DeveloperType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('user');
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => Developer::class
));
}
public function getBlockPrefix() {
return 'backendbundle_developer';
}
}
表单 - 模板
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit" name="{{ form.vars.name }}">Create</button>
{{ form_end(form) }}
表格 - 生成
表单始终隐藏_token
输入字段存在。
<form name="form_name" method="post" class="ui form">
<input type="hidden" name="form_name[_token]" value="YefVvhSvvNTItjw7ayDFwFi4sdf_6oOvsQjnUu9X7cw">
<button type="submit" name="form_name">Create</button>
</form>
(form_name
等于backendbundle_developer
)
用谷歌搜索了几个小时,阅读Stack Overflow上的所有类似问题,包括上述
重新检查文件系统权限
httpd
进程正在_www
用户下运行,因此:
sudo chown -R _www var/
sudo chmod -R 775 var/
会话文件在var/sessions/
成功
更改了app/config/config.yml
条目
session:
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/../var/sessions/%kernel.environment%"
到
session:
handler_id: session.handler.native_file
save_path: ~
根本没有成功。
这不是这些类似问题的重复:
答案 0 :(得分:1)
你应该改变这个
<button type="submit" name="form_name">Create</button>
有了这个
<button type="submit" name="form_name[submit]">Create</button>