How to inject container on FormType in Symfony 3.0?
My services.yml file:
services:
advertiser.form.report:
class: App\AdvertiserBundle\Form\ReportType
arguments: ["@service_container"]
In the action controller:
$report = $this->get( 'advertiser.form.report' );
$form = $this->createForm( $report );
I got this error:
Expected argument of type "string", "App\AdvertiserBundle\Form\ReportType" given
Use form factory instead.
In configuration:
services:
advertiser.form.report:
class: 'Symfony\Component\Form\Form'
factory: ['@form.factory', 'create']
arguments: [App\AdvertiserBundle\Form\ReportType, null, {container: '@service_container'}]
In your form add container
to possible form options:
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'container' => null,
//The rest of options
]);
}
And use it as you want:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$container = $options['container'];
//The rest of logic
}
In your controller, just use form:
$this->get('advertiser.form.report'); //It's a ready-to-use form, you don't need to call $this->createForm()
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