Laurent
Laurent

Reputation: 349

Symfony how to translate data value in a form

I have the following code in a buildForm and I want to obtain the translation of 'report_abuse' but I can't find a way. Is it possible ?

class AbuseType extends AbstractType
{
    // ...

    $builder->add('subject', TextType::class, array(
        'label' => 'label.subject',
        'data' => 'report_abuse',
        'disabled' => 'true',
    ))

    // ...   
 }

Upvotes: 3

Views: 2486

Answers (2)

Laurent
Laurent

Reputation: 349

So this is what I did. I have injected the subject in the Abuse class as its value will be taken by default to build the form. i have also set the field as readonly in place of disabled, which causes the fields to be NOT submitted.

//FormController.php
    class FormController extends Controller
    {
        //...
        public function abuseAction(Request $request)
        {
            $subject = $this->get('translator')->trans('report_abuse');
            $abuse = new Abuse($subject);
           //...
        }
        //...
    }

//Abuse.php
    class Abuse
    {
        //...

        public function __construct($subject)
        {
            $this->setSubject($subject);
        }

    //...
    }

//AbuseType.php
class AbuseType extends AbstractType
{
    //...

    $builder->add('subject', TextType::class, array(
        'label' => 'label.subject',
        'attr' => array(
            'readonly' => true,
        )))

    //...
}

Upvotes: 0

chalasr
chalasr

Reputation: 13167

Try to explicitly set the translation_domain:

$builder->add('subject', TextType::class, array(
    // ...
    'translation_domain' => 'messages',
))

You can also do it for the whole FormType by adding this method into:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{    
    $resolver->setDefaults(array(
        'translation_domain' => 'messages'
    ));
}

If it doesn't work, inject the translator in your FormType by registering it as a service:

# services.yml
services:
    app.form.type.abuse:
        class: AppBundle\Form\Type\AbuseType
        arguments: [ "@translator" ]
        tags:
            - { name: form.type }

Call the translator directly:

use Symfony\Component\Translation\TranslatorInterface;

class AbuseType extends AbstractType
{
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    // ...

    $builder->add('subject', TextType::class, array(
        'label' => 'label.subject',
        'data' => $this->translator->trans('report_abuse', array(), 'messages'),
        'disabled' => 'true',
    ))
}

Upvotes: 2

Related Questions