formssymfonyinternationalizationtranslationchoicefield

Translate select options in Symfony2 class forms


I'm using a class form in Symfony2 Beta3 as follows:

namespace Partners\FrontendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ConfigForm extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('no_containers', 'choice', array('choices' => array(1 => 'yes', 0 => 'no')));
        ...

I want to translate the 'yes' and 'no' options, but I don't know how to use the translator here.


Solution

  • You can use the translation resources as usual. This worked for me:

        $builder->add('sex', 'choice', array( 
            'choices'   => array(
                1 => 'profile.show.sex.male', 
                2 => 'profile.show.sex.female',
            ),
            'required' => false,
            'label'     => 'profile.show.sex.label',
            'translation_domain' => 'AcmeUserBundle'
        ));
    

    And then add your translations to the Resources->translations directory of your Bundle.

    Update from @CptSadface:

    In symfony 2.7, using the choice_label argument, you can specify the translation domain like this:

    'choice_label' => 'typeName',
    'choice_translation_domain' => 'messages',
    

    Without specifying the domain, options are not translated.