Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access other services inside a Symfony FormType?

I try to access a service from a FormType extended by AbstractType. How can I do that?

Thanks!

like image 924
Gerrit Avatar asked Aug 08 '13 13:08

Gerrit


3 Answers

As a complete answer based on previous answers/comments:

In order to access to a service from your Form Type, you have to:

1) Define your Form Type as a service and inject the needed service into it:

# src/AppBundle/Resources/config/services.yml
services:
    app.my.form.type:
        class: AppBundle\Form\MyFormType # this is your form type class
        arguments:
            - '@my.service' # this is the ID of the service you want to inject
        tags:
            - { name: form.type }

2) Now in your form type class, inject it into the constructor:

// src/AppBundle/Form/MyFormType.php
class MyFormType extends AbstractType
{
    protected $myService;

    public function __construct(MyServiceClass $myService)
    {
        $this->myService = $myService;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->myService->someMethod();
        // ...
    }
}
like image 149
Francesco Borzi Avatar answered Nov 19 '22 10:11

Francesco Borzi


Just inject services you want through constructor to the form type.

class FooType extends AbstractType
{
    protected $barService;

    public function __construct(BarService $barService)
    {
        $this->barService = $barService;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->barService->doSomething();
        // (...)
    }
}
like image 22
Cyprian Avatar answered Nov 19 '22 09:11

Cyprian


Look at this page in the sympfony docs for a description of how to declare your form type as a service. That page has a lot of good documentation and example.

Cyprian is on the right track, but the linked page takes it a step further by creating your form type as a service and having the DI container inject the service automatically.

like image 3
Icode4food Avatar answered Nov 19 '22 09:11

Icode4food