pogeybait
pogeybait

Reputation: 3145

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

I have a form type:

<?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',
        ));
    }
}

As you see I am already attempting to set up my form type to inject the translator. In my services I have:

parameters:
#    parameter_name: value

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

But am receiving the following error:

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....

Can someone tell me what gives? I am pretty sure the service type is wrong but cant find the one I need to save my life.

Upvotes: 2

Views: 2070

Answers (1)

Matteo
Matteo

Reputation: 39390

Check in the service definition of your form that you have correctly tag the service as a form.type as described here in the doc.

In according with the news announcement, from the version 2.6 the translator component is defined as service like translator.default.

As Example, you should have something like:

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

hope this help

Upvotes: 2

Related Questions