Symfony2 - 将集合类型表单定义为服务

时间:2017-03-10 16:30:13

标签: php doctrine-orm symfony symfony2-forms

我想在我的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 \表格\型号\ ChildType :: __结构()   必须是一个实例   Doctrine \ ORM \ EntityManager,没有给出,调用   在   C:\ XAMPP \ htdocs中\ trainingexperience_symfony \供应商\ symfony的\ symfony中的\ src \的Symfony \分量\表格\ FormRegistry.php   在第90行并定义

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

1 个答案:

答案 0 :(得分:2)

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

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

希望这个帮助