Symfony - Inject Entity Manager in EventSubscriber of form

前端 未结 1 1854

This is the first time I am working with EventListener of a form so I am struggling on how to inject EntityManager in it.

I have this formType called UserType<

相关标签:
1条回答
  • 2021-01-19 10:24

    It's because, you pass new instance of AddDepartmentDegreeCourseFieldSubscriber when building form. You need to pass instance from service container.

    use AppBundle\Form\EventListener\AddDepartmentDegreeCourseFieldSubscriber;
    
    class UserType extends AbstractType
    {
        private $addDepartmentDegreeCourseFieldSubscriber;
    
        public function __construct(AddDepartmentDegreeCourseFieldSubscriber $subscriber)
        {
            $this->addDepartmentDegreeCourseFieldSubscriber = $subscriber;
        }
    
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->addEventSubscriber($this->addDepartmentDegreeCourseFieldSubscriber);
        }
    }
    
    # app/config/services.yml
    services:
        app.department_course_degree_subscriber:
            class: AppBundle\Form\EventListener\AddDepartmentDegreeCourseFieldSubscriber
            arguments: ["@doctrine.orm.entity_manager"]
            tags:
                - { name: kernel.event_subscriber }
    
        app.form.type.my_user_form:
            class: AppBundle\Form\UserType
            arguments: [ "@app.department_course_degree_subscriber" ]
            tags:
                - { name: form.type }
    
    0 讨论(0)
提交回复
热议问题