Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 - Define form as a service

in my Symfony 3-master project, I use this code to create a form in a controller:

$form = $this->createForm(ApplicantType::class, $applicant);

Now I decided to make a service out of this form, so I can use EntityManager inside of it. So in Symfony2.x, this would be pretty easy, just with a declaration in services.yml and this line of code:

$form = $this->createForm($this->get("applicant.form"), $applicant);

However, this is no longer possible in Symfony 3, because this first parameter expect a string, not the form itself.

So my question is: How do I create a form as a service in Symfony 3, or is there any other way how to pass EntityManager inside of the form?

Thank you for any help!

like image 962
Mike Avatar asked Oct 31 '15 12:10

Mike


2 Answers

Defining a form type as service does not imply passing the instance retrieved from to container to createForm. when doing this, the container is not involved as far as the form component is involved.

To use a form type registered as a service (with the form.type tag so that the form component knows about it), you just just reference it by its name (i.e. the fully qualified class name in Symfony 2.8+ and the type name in older versions) in createForm or in FormBuilder::add. This is exactly what you do for Symfony core types btw (text, choice and so on), which are registered as services. the code of your controller does not change at all when using the form type as a service rather than having a form type without dependency and registered implicitly on first usage.

like image 113
Christophe Coevoet Avatar answered Oct 19 '22 05:10

Christophe Coevoet


This is what i did to inject a form as a service in Symfony 3 from my Symfony 2 Code.

In my service.yml i changed

issue.form:
    class: Gutersohn\Bundle\CoreBundle\Form\IssueType
    arguments: ['@service_container']
    tags:
        - { name: form.type, alias: issue }

to

issue.form:
    class: Gutersohn\Bundle\CoreBundle\Form\IssueType
    arguments: ['@service_container']
    tags:
        - { name: form.type }

In my controller i changed

$form = $this->container->get('form.factory')->create($this->container->get('issue.form'), $issue, [
        "method" => "post",
        "action" => $this->container->get('router')->generate("ticket_add")
]);

to

$form = $this->container->get('form.factory')->create(IssueType::class, $issue, [
        "method" => "post",
        "action" => $this->container->get('router')->generate("ticket_add")
]); 
like image 6
Patric Robert Gutersohn Avatar answered Oct 19 '22 03:10

Patric Robert Gutersohn