I try to access a service from a FormType extended by AbstractType. How can I do that?
Thanks!
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();
// ...
}
}
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();
// (...)
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With