Search code examples
symfonylocalization

Symfony2 - Set translation domain for a whole form


I want to translate a form created with symfony's formbuilder. As i don't want one big translation file it is splitted up into "domains".

Now i have to specify the translation_domain for each form-field, otherwise symfony will look in the wrong file. This option has to be added to every field and i'm wondering if there is a way to set this option to a whole form?

Sample code i'm not happy with:

$builder->add(
    'author_name',
    'text',
    array('label' => 'Comment.author_name', 'translation_domain' => 'comment')
)->add(
    'email',
    'email',
    array('label' => 'Comment.email', 'translation_domain' => 'comment')
)->add(
    'content',
    'textarea',
    array('label' => 'Comment.content', 'translation_domain' => 'comment')
);

Solution

  • You've then to set it as a default option of your form, add this:

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

    to your setDefaultOptions method, in your form.

    Update: It is deprecated. Use configureOptions method instead (thanks @Sudhakar Krishnan)