无法在我的 formType 中加载 TranslatorInterface

cannot load the TranslatorInterface in my formType

我尝试将一些翻译引入 ChatBundle 以跟上 Symfony 4 中托管应用 _locale 的变化。

所以在 formBuilder 中,我尝试这样注入 TranslatorInterface

// lib/ChatBundle/Form/ChatMessageType.php

namespace bornToBeAlive\ChatBundle\Form;

use bornToBeAlive\ChatBundle\Entity\ChatMessage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;

class ChatMessageType extends AbstractType
{
    private $trans;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('content', null, [
                'attr'=> ['placeholder' => $this->trans->trans('placeholder',[],'chat')]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => ChatMessage::class,
        ]);
    }
}

但是当我尝试 运行 我的 show 操作时:

public function show(): Response
{
    $message = new ChatMessage();

    $form = $this->createForm(ChatMessageType::class, $message);

    return $this->render('@Chat/show.html.twig', [
        'form' => $form->createView(),
    ]);
}

我收到以下错误:

Too few arguments to function bornToBeAlive\ChatBundle\Form\ChatMessageType::__construct(), 0 passed in ../vendor/symfony/form/FormRegistry.php on line 92 and exactly 1 expected

我很惊讶,因为我在其他类型的主机应用程序中使用了这种技术。我做错了什么吗?

根据 Symfony 4.4 Form documentation :

If you're using the default services.yaml configuration, this example will already work! Otherwise, create a service for this form class and tag it with form.type.

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      
        autoconfigure: true 
        public: false 

如果自动装配没有按预期工作,您可以像这样将表单定义为服务

# config/services.yaml
app.form.corporation_type:
    class: bornToBeAlive\ChatBundle\Entity\ChatMessageType
    arguments: ["@translator"]
    tags:
        - { name: form.type }