Reputation: 947
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
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
Reputation: 31919
/**
* 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
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
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