3

How could I get entity manager when building forms?

I would like to search results from the database and build the choices for choicetype. I know I could use entitytype instead but in this situation I want to record string in database than an object. And also I need to add some more options as well.

Thank you.

Bob
  • 71
  • 1
  • 11
  • you can inject entity manager as a form type constructor and pass entity manager when you create form, like `$em = $this->getDoctrine()->getManager(); $form = $this->createForm(new YourFormType($em), $entity, array( 'action' => $this->generateUrl('your_url'), 'method' => 'POST', )); ` – habibun Mar 30 '17 at 04:30
  • Wow, cool. I will try that later. Currently I just use a private function in controller to build the form instead of previous Form Type. Thanks a lot, habibun. – Bob Mar 30 '17 at 06:51

1 Answers1

10

In Symfony 3.2 (and possibly others, I'm not sure about 3.1, but it is probably the same), the $this->createForm() method needs a string as the first parameter, and cannot take a form object.

Add a configureOptions method to your form class:

class YourFormType extends AbstractType
{

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'entityManager' => null,
        ]);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Entity Manager is set in: $options['entityManager']
    }
}

Then get the form in your controller like so, passing in the Entity Manager:

$form = $this->createForm(
     YourFormType::class,
     $yourEntity,
     [
         'entityManager' => $this->getDoctrine()->getManager(),
     ]
);
Luke Cousins
  • 2,068
  • 1
  • 20
  • 38