Alex B.
Alex B.

Reputation: 947

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')
);

Upvotes: 21

Views: 21923

Answers (4)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

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)

Upvotes: 59

Mick
Mick

Reputation: 31919

Symfony 3

/**
 * Configures the options for this type.
 *
 * @param OptionsResolver $resolver The resolver for the options.
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'translation_domain' => 'forms',
        // Add more defaults if needed
    ));
}

Upvotes: 3

Jordon
Jordon

Reputation: 547

The method name in Ahmed's answer is now deprecated (since Symfony 2.7), the 2.7+ way of doing it is:

/**
 * Configures the options for this type.
 *
 * @param OptionsResolver $resolver The resolver for the options.
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefault('translation_domain', 'messages');
}

in the same way you set your data_class settings, etc.

To do this using just the form builder, there is an options argument on the form builder. From the controller, for example:

$form = $this->createFormBuilder($entity, ['translation_domain' => 'messages'])->add(..)->getForm();

If you're using the FormFactory service, this would be

$formFactory->createBuilder('form', $entity, ['translation_domain' => 'messages']);

Upvotes: 26

Rvanlaak
Rvanlaak

Reputation: 3085

Or in case you use the Factory's namedBuilder that would be:

$formBuilder = $this->get('form.factory')->createNamedBuilder('myForm', 'form', $data, array(
    'translation_domain' => 'forms',
));

Upvotes: 2

Related Questions