Inject EntityManager into embedded FormTypes with Symfony2 3.0+ Inject EntityManager into embedded FormTypes with Symfony2 3.0+ symfony symfony

Inject EntityManager into embedded FormTypes with Symfony2 3.0+


OK I figured this out with @Cerad

app.form.a:    class: AppBundle\Form\AType    arguments: ["@doctrine.orm.entity_manager"]    tags:        - { name: form.type, alias: app.form.a }app.form.b:    class: AppBundle\Form\BType    arguments: ["@doctrine.orm.entity_manager"]    tags:        - { name: form.type, alias: app.form.b }app.form.c:    class: AppBundle\Form\CType    arguments: ["@doctrine.orm.entity_manager"]    tags:        - { name: form.type, alias: app.form.c }

And then in the controller when you call:

$form = $this->createForm(AType::class, $a);

Apparently Symfony2 in the background looks for the service and injects the dependencies, my confusion was that before you had to call the service yourself when using createForm... I did not see any documentation about this..

Then, in the types when you do:

private $em;public function __construct(EntityManager $em){    $this->em = $em;}/** * @param FormBuilderInterface $builder * @param array $options */public function buildForm(FormBuilderInterface $builder, array $options){    $builder        ->add('b', BType::class)    ;}

Symfony will take care of injecting the dependencies of BType as well if you define it as a service.

Thanks @Cerad! your comment made me perform this test!