How to access other services in Symfony FormType?

I am trying to access a service from FormType extended by AbstractType. How can i do this?

Thanks!

+7
symfony
source share
3 answers

Just enter the services you want through the constructor into 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(); // (...) } } 
+4
source share

As a complete answer based on previous answers / comments:

To access the service from your form type, you need to:

1) Define your type of form as a service and enter the necessary 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 the form type class, enter it in 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(); // ... } } 
+5
source share

See this page in sympfony docs for a description of how to declare your form type as a service. There is a lot of good documentation and an example on this page.

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

+3
source share

All Articles