Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 Inject Container in FormType

Tags:

php

symfony

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

like image 611
Siol Avatar asked Dec 29 '15 15:12

Siol


1 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()
like image 77
E.K. Avatar answered Oct 29 '22 01:10

E.K.