Passing data to buildForm() in Symfony 2.8, 3.0 and above

后端 未结 4 1339
暗喜
暗喜 2020-11-27 11:36

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

4条回答
  •  时光取名叫无心
    2020-11-27 12:26

    This broke some of our forms as well. I fixed it by passing the custom data through the options resolver.

    In your form type:

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

提交回复
热议问题