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

后端 未结 4 1348
暗喜
暗喜 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:37

    Here can be used another approach - inject service for retrieve data.

    1. Describe your form as service (cookbook)
    2. Add protected field and constructor to form class
    3. Use injected object for get any data you need

    Example:

    services:
        app.any.manager:
            class: AppBundle\Service\AnyManager
    
        form.my.type:
            class: AppBundle\Form\MyType
            arguments: ["@app.any.manager"]
            tags: [ name: form.type ]
    

    manager = $manager;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $choices = $this->manager->getSomeData();
    
            $builder
                ->add('type', ChoiceType::class, [
                    'choices' => $choices
                ])
            ;
        }
    
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'data_class' => 'AppBundle\Entity\MyData'
            ]);
        }
    
    }
    

提交回复
热议问题