【问题标题】:Symfony2 - define collection type form as a serviceSymfony2 - 将集合类型定义为服务
【发布时间】:2017-03-10 16:30:13
【问题描述】:

我想以PRE_SET_DATA 事件监听器的形式使用服务。现在这个表单被嵌入到另一个表单类型CollectionType

class ChildType extends AbstractType
{
    private $entitymanager;

    public function __construct(EntityManager $entitymanager)
    {
        $this->entityManager = $entitymanager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ...     

        // Add listeners
        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
    }

    public function onPreSetData(FormEvent $event)
    {
        $form = $event->getForm();

        ...

        $this->entityManager->flush();
    }

    ...
}

为了注入实体管理器服务,我将表单类型定义为服务:

services:
    form_type_child:
        class: IndexBundle\Form\Type\ChildType
        arguments:
            - @doctrine.orm.entity_manager

现在我必须将此表单用作CollectionType

class ParentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
             ->add('child', CollectionType::class, array(
                'type' => ChildType::class,
                'by_reference' => false,
                'required' => false
             ))
            ->add('submit', SubmitType::class);
    }
}

现在我收到此错误:

可捕获的致命错误:参数 1 传递给 IndexBundle\Form\Type\ChildType::__construct() 必须是 Doctrine\ORM\EntityManager,没有给出,调用 在 C:\xampp\htdocs\trainingexperience_symfony\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php 在第 90 行并定义

任何想法如何以CollectionType 嵌入形式传递实体管理器?

【问题讨论】:

    标签: php doctrine-orm symfony symfony2-forms


    【解决方案1】:

    您需要将服务标记为表单:

    services:
        form_type_child:
            class: IndexBundle\Form\Type\ChildType
            arguments:
                - @doctrine.orm.entity_manager
            tags:
                - { name: form.type }
    

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多