Home » Php » php – Symfony 3 Inject Container in FormType

php – Symfony 3 Inject Container in FormType

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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()

Answer:

As in comments, the fix is easy; you should only do:

$form = $this->createForm(ReportType::class);

Anyhow, I would highly discourage you from injecting the whole container in ANY kind of class. It’s better to inject only the needed service.