Symfony2 - 将集合类型形式定义为服务

Symfony2 - define collection type form as a service

我想在我的表单 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);
    }
}

现在我得到这个错误:

Catchable Fatal Error: Argument 1 passed to IndexBundle\Form\Type\ChildType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in C:\xampp\htdocs\trainingexperience_symfony\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 90 and defined

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

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

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

希望对您有所帮助