如何在 Symfony 3 的控制器之外使用翻译服务?

How can I use the Translator service outside of a controller in Symfony 3?

我有一个表格类型:

<?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, none given, called in /path/to/symfony/bundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php on line 85 and defined....

有人能告诉我是什么吗?我很确定服务类型有误,但找不到我需要的服务类型。

检查表单的服务定义是否已正确将服务标记为 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 }

希望对您有所帮助