Forms 转换Symfony2类表单中的选择选项

Forms 转换Symfony2类表单中的选择选项,forms,symfony,internationalization,translation,choicefield,Forms,Symfony,Internationalization,Translation,Choicefield,我在Symfony2 Beta3中使用了一个类表单,如下所示: namespace Partners\FrontendBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; class ConfigForm extends AbstractType { public function buildForm(FormBuilder $builder, arr

我在Symfony2 Beta3中使用了一个类表单,如下所示:

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

我想翻译“是”和“否”选项,但我不知道如何在此处使用翻译器。

我搜索了一段时间以找到答案,但最终我发现Symfony是如何翻译表单内容的。在您的情况下,最简单的方法似乎是通过将YAML或XLIFF翻译文件添加到您的应用程序(例如app/Resources/translations/messages.de.yml)或您的捆绑包中来添加“yes”和“no”的翻译。这里描述了这一点:

在我看来,问题在于您似乎无法使用自定义翻译键。FOSUserBundle的人用“表单主题”()解决了这个(或类似的)问题。下面是实现将表单元素id用作翻译键的两行重要代码:

/

通过添加表单主题,您可以修改模板中几乎所有的表单-这似乎是正确的方法


(很抱歉,我不得不拆分两个链接b/c我没有足够的声誉发布两个以上的链接。很遗憾。)

你可以像往常一样使用翻译资源。这对我很有用:

    $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'
    ));
然后将您的翻译添加到捆绑包的Resources->translations目录中

从@CptSadface更新:

在symfony 2.7中,使用choice_label参数,可以如下指定翻译域:

'choice_label' => 'typeName',
'choice_translation_domain' => 'messages',
'choice_label' => 'typeName',
'choice_translation_domain' => 'messages',
如果不指定域,则不会翻译选项。

在symfony 2.7中,使用choice_label参数,可以如下所示指定翻译域:

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

如果不指定域,则不会转换选项。

CptSadface的答案帮助我转换实体选择

$builder
    ->add(
        'authorizationRoles',
        null,
        [
            'label' => 'app.user.fields.authorization_roles',
            'multiple' => true,
            'choice_label' => 'name', // entity field storing your translation key
            'choice_translation_domain' => 'messages',
        ]
    );

我忘了添加所有默认表单主题的URL-一个很好的参考:其中一个链接断开了。我修复了断开的链接。这是真正的答案+1我已保存了一封具有多元化功能的翻译邮件。是否可以在表单类型代码(如@bingen)中定义要使用的计数?例如“[…]数组(1=>'profile.show.sex.male{count=3}”,2=>'profile.show.sex.male')[…]”。因为我有一个问题,仅仅提供消息名就可以显示整个消息,而不仅仅是一个默认消息(“{0}Links{1}Link}]1,+Inf[Links”),我忘记了:不需要显式地注入容器或翻译服务。这有点元,但其中一个选项不应该是“女性”?我知道我们在一个与计算机科学相关的网站上,但仍然…@webyseo,正如我在最初的回答中所说的,在参考资料->翻译文件夹中(很抱歉延迟回复,我有点断开了连接),谢谢CptSadface和@jxmallett!