将数据传递到Symfony 2.8、3.0及更高版本中的buildForm() [英] Passing data to buildForm() in Symfony 2.8, 3.0 and above

查看:59
本文介绍了将数据传递到Symfony 2.8、3.0及更高版本中的buildForm()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此答案中的建议,我的应用程序当前正在使用构造函数将数据传递到表单类型.但是, 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('name', TextType::class, ['label' => 'L_PROFILE_EDIT_NAME', 'required' => false])
        ...
        ->add('figure_type', ChoiceType::class, [
            'label' => 'L_PROFILE_EDIT_FIGURETYPE',
            'mapped' => false,
            'choices' => $this->traitChoices['figure_type']
        ])
        ...
    ;
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Foo\BarBundle\Entity\Profile',
        '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, array(
        'action' => $this->generateUrl('profile_update'),
        'method' => 'PUT',
        'trait_choices' => $traitChoices,
    ));

这篇关于将数据传递到Symfony 2.8、3.0及更高版本中的buildForm()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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