user1336101
user1336101

Reputation: 441

Symfony3 Form class Entity Manager

I have trouble with migration to Symfony3. I have a form in FormType class and I pass Entity manager throught constructor.

Here is example of code: Controller

$form = $this->createForm(new SubjectType($emDefault));

Form Class

class SubjectType extends AbstractType {
    private $em;
    public function __construct($em) {
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {        
        $builder
                ->add('subject', 'entity', array(
                    'em' => $this->em,
                    'class' => 'MyBundle:Subject',
                    'query_builder' => function ($em) {
                        return $em->createQueryBuilder('s')
                        ->where('s.active = 1');
                    },
                    'property' => 'name')
                )
                ->add('create', 'submit', array('label' => 'choose'));
    }
    ...

Symfony 3 has change in method createForm to:

$this->createForm(SubjectType::class);

And with this declaration, I don't know how to pass entity manager to form class.

Anyone help, please?

Upvotes: 1

Views: 1236

Answers (1)

chalasr
chalasr

Reputation: 13167

You need to declare your FormType as a service.

services.yml

services:
    app.form.type.subject:
        class: AppBundle\Form\Type\SubjectType
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - { name: form.type }

Re-add the commented line in your constructor and you'll be able to use $this->em as in previous versions.

Upvotes: 2

Related Questions