Search code examples
symfonytwigsymfony-formssymfony-3.3

How to translate Symfony 3 forms?


Translating content in twig templates seems easy and straightforward: I run bin/console translation:update to populate translation files. The issue is that it seems to ignore forms.

After creating entities, repositories and forms/types, I use {{ form_row(form.field) }} in twig templates to draw the form elements.

Is there a well-established practice on how to customize and translate form labels, placeholders and errors messages?

Must I use form_label and form_widget instead of form_row to customize labels?


Solution

  • You could create for example a file named forms.es.yml here, you can put you traductions in spanish, and in your forms you can chain it like this:

    //LoginType.php
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email',
                EmailType::class,
                [
                    'translation_domain' => 'forms', //It's translate the label
                    'constraints' => [
                        new Email([
                            'message' => 'email'
                        ])
                    ]
                ]
            )
            ->add('password',
                RepeatedType::class,
                [
                    'type' => PasswordType::class,
                    'invalid_message' => 'cliente.password_not_equal',
                    'first_options' => ['label' => 'cliente.password'],
                    'second_options' => ['label' => 'cliente.repeat_password'],
                    'translation_domain' => 'forms', //Here is again
                    'constraints' => [
                        new NotBlank([
                            'message' => 'not_blank'
                        ])
                    ]
                ]
            )
            ->add('current_uri', HiddenType::class);
    }
    

    It works since symfony 2.

    Another way is in your twig, only print the widget and translate the label:

    //index.html.twig
    <label> 
       {{'form.email'|trans({})}}
       {{ form_widget('form.email') }} //It only prints the input tag
    </label>
    

    Is an easy way, but is less reusable.