douli1872 2016-03-20 07:56
浏览 65

Symfony访问EventSubscriber中的实体管理器

I have an Employer profile form and I am trying to link the State where Employer is located at with a City this part is working alright but the FormType got so long and this feature will be required at other places of the website so I decided to move this logic inside an EventSubscriber and reuse it where ever I need it.

Problem I am having is I am trying to wrap my head around how to inject EntityManager inside the EventSubscriber class.

I know I can add the following code inside my services.yml and that should do it buts its not working.

app.form.location:
    class: AppBundle\Form\EventListener\AddStateFieldSubscriber
    arguments: ['@doctrine.orm.entity_manager']
    tags:
        - { name: kernel.event_subscriber }

This is my EmployerProfileType where I am calling my addEventSubscriber which is AddStateFieldSubscriber()

class EmployerProfileType extends AbstractType
{
    protected $em;

    function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class)
            ->add('lastName', TextType::class)
            ->add('companyName', TextType::class)
            ->add('companyProfile', TextareaType::class)
            ->add('companyLogo', FileType::class, array(
                'data_class' => null
            ));
        $builder->addEventSubscriber(new AddStateFieldSubscriber());

    }


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\EmployerProfile',

        ));
    }


    public function getName()
    {
        return 'app_bundle_emp_profile_type';
    }
}

This is my AddStateFieldSubscriber class where I need access to EntityManager

class AddStateFieldSubscriber implements EventSubscriberInterface
{

    protected $em;

    function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        // Tells the dispatcher that you want to listen on the form.pre_set_data
        // event and that the preSetData method should be called.
        return array(
            FormEvents::PRE_SET_DATA => 'onPreSetData',
            FormEvents::PRE_SUBMIT => 'onPreSubmit'
            );
    }
    protected function addElements(FormInterface $form, States $province = null)
    {
        // Remove the submit button, we will place this at the end of the form later
        // Add the province element
        $form->add('state', EntityType::class, array(
                'data' => $province,
                'placeholder' => 'provide_state',
                'class' => 'AdminBundle\Entity\States',
                'mapped' => false)
        );
        // Cities are empty, unless we actually supplied a province
        $cities = array();
        if ($province) {
            // Fetch the cities from specified province
            $repo = $this->em->getRepository('AdminBundle:Cities');
            $cities = $repo->findByStates($province, array('name' => 'asc'));
        }
        // Add the city element
        $form->add('city', EntityType::class, array(
            'placeholder' => 'provide_state_first',
            'class' => 'AdminBundle\Entity\Cities',
            'choices' => $cities,
        ));

    }
    function onPreSubmit(FormEvent $event) {
        $form = $event->getForm();
        $data = $event->getData();

        // Note that the data is not yet hydrated into the entity.
        $province = $this->em->getRepository('AdminBundle:States')->find($data['state']);
        $this->addElements($form, $province);
    }
    function onPreSetData(FormEvent $event) {
        $account = $event->getData();
        $form = $event->getForm();

        // We might have an empty account (when we insert a new account, for instance)
        $province = $account->getCity() ? $account->getCity()->getStates() : null;
        $this->addElements($form, $province);
    }
}

The error I get is

Catchable Fatal Error: Argument 1 passed to AppBundle\Form\EventListener\AddStateFieldSubscriber::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /Users/shairyar/Sites/clickjobboard/src/AppBundle/Form/EmployerProfileType.php on line 48 and defined

I am injecting EntityManager via service then why do I get this error?

If inside EmployerProfileType I replace

$builder->addEventSubscriber(new AddStateFieldSubscriber(); to $builder->addEventSubscriber(new AddStateFieldSubscriber($this->em));

then things start working fine.

I thought in Symfony we are supposed to inject the dependencies by creating services? So how can I inject EntityManager inside my AddStateFieldSubscriber() class

What am i doing wrong? may be I am over thinking about it.

Will appreciate any feedback.

  • 写回答

1条回答 默认 最新

  • duanlu7223 2016-03-20 09:39
    关注

    I think you need to tag your AddStateFieldSubscriber as kernel.event_subscriber.

    Then the binding inside the form in not needed at all.

    Instead you need to check for the correct form, and jump out of the event listener method if the form is not one of your forms using that subscriber, since the Event would be triggered on any form then, not only the EmployerProfileType form.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图