【问题标题】:How can I use the Translator service outside of a controller in Symfony 3?如何在 Symfony 3 的控制器之外使用 Translator 服务?
【发布时间】:2016-08-09 09:39:32
【问题描述】:

我有一个表单类型:

<?php

// src/AppBundle/Form/ProductType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class ProductType extends AbstractType
{

    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('save', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product',
        ));
    }
}

如您所见,我已经在尝试设置我的表单类型来注入翻译器。在我的服务中,我有:

parameters:
#    parameter_name: value

services:
    app.form.product:
        class: AppBundle\Form\ProductType
        arguments: ["@translator"]

但收到以下错误:

Catchable Fatal Error: Argument 1 passed to AppBundle\Form\ProductType::__construct() must implement interface

Symfony\Component\Translation\TranslatorInterface,没有给出,调用 在 /path/to/symfony/bundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php 在第 85 行并定义....

谁能告诉我什么给了?我很确定服务类型是错误的,但找不到我需要挽救生命的服务类型。

【问题讨论】:

    标签: php symfony symfony-forms


    【解决方案1】:

    检查表单的服务定义,您已将服务正确标记为 form.type,如 here in the doc 所述。

    根据news announcement,从2.6版开始,翻译器组件被定义为translator.default之类的服务。

    作为示例,您应该有类似的内容:

    services:
        app.form.product:
            class: AppBundle\Form\ProductType
            arguments: ["@translator.default"]
            tags:
                - { name: form.type }
    

    希望有帮助

    【讨论】:

    • 缺少“标签”参数使其无法正常工作。我还必须“使用 Symfony\Bundle\FrameworkBundle\Translation\Translator;”而不是我上面的代码中的 TranslatorInterface 。谢谢一捆。此外,使用控制台命令:“bin/console debug:container”有助于找出哪些服务是可注入的,并有助于找到要使用的“使用”语句。
    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多