在 Symfony 2.8、3.0 及更高版本中将数据传递给 buildForm() [英] Passing data to buildForm() in Symfony 2.8, 3.0 and above
问题描述
我的应用程序当前使用构造函数将数据传递给我的表单类型,如此答案中所推荐.然而,Symfony 2.8 升级指南 建议将类型实例传递给createForm
函数已弃用:
My application currently passes data to my form type using the constructor, as recommended in this answer. However the Symfony 2.8 upgrade guide advises that passing a type instance to the createForm
function is deprecated:
将类型实例传递给 Form::add()、FormBuilder::add() 和FormFactory::create*() 方法已弃用,将不受支持不再在 Symfony 3.0 中.传递完全限定的类名输入.
Passing type instances to Form::add(), FormBuilder::add() and the FormFactory::create*() methods is deprecated and will not be supported anymore in Symfony 3.0. Pass the fully-qualified class name of the type instead.
Before:
$form = $this->createForm(new MyType());
After:
$form = $this->createForm(MyType::class);
既然我无法使用完全限定的类名传递数据,那么还有替代方法吗?
Seeing as I can't pass data through with the fully-qualified class name, is there an alternative?
推荐答案
这也破坏了我们的一些表单.我通过选项解析器传递自定义数据来修复它.
This broke some of our forms as well. I fixed it by passing the custom data through the options resolver.
在您的表单中输入:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->traitChoices = $options['trait_choices'];
$builder
...
->add('figure_type', ChoiceType::class, [
'choices' => $this->traitChoices,
])
...
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'trait_choices' => null,
]);
}
然后,当您在控制器中创建表单时,将其作为选项而不是构造函数传入:
Then when you create the form in your controller, pass it in as an option instead of in the constructor:
$form = $this->createForm(ProfileEditType::class, $profile, [
'trait_choices' => $traitChoices,
]);
这篇关于在 Symfony 2.8、3.0 及更高版本中将数据传递给 buildForm()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!