簡體   English   中英

FormType中的Symfony 3注入容器

[英]Symfony 3 Inject Container in FormType

如何在Symfony 3.0中的FormType上注入容器?

我的services.yml文件:

services:
    advertiser.form.report:
        class: App\AdvertiserBundle\Form\ReportType
        arguments: ["@service_container"]

在動作控制器中:

$report = $this->get( 'advertiser.form.report' );
$form = $this->createForm( $report );

我收到此錯誤:

給定類型為“ string”,“ App \\ AdvertiserBundle \\ Form \\ ReportType”的預期參數

請改用表單工廠。

在配置中:

services:
    advertiser.form.report:
        class:  'Symfony\Component\Form\Form'
        factory: ['@form.factory', 'create']
        arguments: [App\AdvertiserBundle\Form\ReportType, null, {container: '@service_container'}]

在表單中,將container添加到可能的表單選項中:

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'container' => null,
        //The rest of options
    ]);
}

並根據需要使用它:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $container = $options['container'];
    //The rest of logic
}

在您的控制器中,只需使用以下形式:

$this->get('advertiser.form.report'); //It's a ready-to-use form, you don't need to call $this->createForm()

如評論中所述,修復很容易; 您應該只做:

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

無論如何,我強烈建議您不要將整個容器注入任何類的容器中。 最好只注入所需的服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM