1

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?

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I found this earlier in documentation but I had some other errors in my code, so this solutions doesn't work for me, but now I used it and it is But now it finally works :)
If you want, create another question with your error trace, I'll be glad to debug with you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.