user3076049
user3076049

Reputation:

Symfony2 - define collection type form as a service

I would like to use a service in my form PRE_SET_DATA event listener. Now this form is embedded into another form type as 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();
    }

    ...
}

To inject entity manager service I defined form type as a service:

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

And now I have to use this form as a 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);
    }
}

Now I get this error:

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

Any ideas how can I pass entity manager in CollectionType embedded form?

Upvotes: 2

Views: 246

Answers (1)

Matteo
Matteo

Reputation: 39470

You need to tag the service as a form:

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

Hope this help

Upvotes: 1

Related Questions