gpt4 book ai didi

php - 在 Symfony 2.8、3.0 及更高版本中将数据传递给 buildForm()

转载 作者:IT老高 更新时间:2023-10-28 11:56:01 24 4
gpt4 key购买 nike

我的应用程序当前使用构造函数将数据传递给我的表单类型,正如 this answer 中的建议。 .然而 Symfony 2.8 upgrade guide建议不推荐将类型实例传递给 createForm 函数:

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);

看到我无法使用完全限定的类名传递数据,是否有替代方法?

最佳答案

这也破坏了我们的一些表格。我通过选项解析器传递自定义数据来修复它。

在您的表单类型中:

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,
]);
}

然后,当您在 Controller 中创建表单时,将其作为选项而不是在构造函数中传递:

$form = $this->createForm(ProfileEditType::class, $profile, [
'trait_choices' => $traitChoices,
]);

关于php - 在 Symfony 2.8、3.0 及更高版本中将数据传递给 buildForm(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34027711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com