带有构造参数的 Symfony 3 createForm [英] Symfony 3 createForm with construct parameters

查看:39
本文介绍了带有构造参数的 Symfony 3 createForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Symfony 2.8 开始,您只能将 FQCN 传递到控制器的 createForm 方法中.所以,我的问题是,当我在控制器中创建表单时,如何将构造参数传递到表单类构造中?

Since Symfony 2.8, you can only pass the FQCN into the controller createForm method. So, my question is, how do I pass construct parameters into the form class construct when I create the form in the controller?

< Symfony 2.8 I could do (MyController.php):

$this->createForm(new MyForm($arg1, $arg2));

Symfony 2.8+ 我只能做(MyController.php):

Symfony 2.8+ I can only do (MyController.php):

$this->createForm(MyForm::class);

那么我怎样才能传入我的构造参数呢?这些参数在控制器操作中提供,因此我无法使用表单即服务"方法...

So how can I pass in my construct arguments? These arguments are provided in the controller actions so I can't use the "Forms as services" method...

推荐答案

简单地:

$this->createForm(MyForm::class, $entity, ['arg1' => $arg1, 'arg2' => $arg2]);

无论如何,这实际上应该在 2.8 之前完成.

which is actually how it should have been done prior to 2.8 anyway.

编辑

根据您的评论,您需要在类类型本身中设置默认值:

based upon your comment, you need to set up the default values in the class type itself:

public function configureOptions( OptionsResolver $resolver ) {
    $resolver->setDefaults( [
      'arg1' => null,
      'arg2' => null,
    ] );
}

这篇关于带有构造参数的 Symfony 3 createForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆