29

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

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

4

4 回答 4

88

您可以照常使用翻译资源。这对我有用:

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

然后将您的翻译添加到 Bundle 的 Resources->translations 目录中。

来自@CptSadface 的更新:

symfony 2.7中,使用choice_label 参数,您可以像这样指定翻译域:

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

如果不指定域,则不会翻译选项。

于 2013-01-04T02:00:05.610 回答
4

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

问题 - 在我看来 - 是您似乎无法使用自定义翻译键。FOSUserBundle 的人用“表单主题”(http://symfony.com/doc/2.0/cookbook/form/form_customization.html)解决了这个(或类似的)问题。这里有两行重要的代码来实现使用表单元素 id 作为翻译键:

https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/views/Registration/register_content.html.twig#L1 / https://github.com/FriendsOfSymfony/FOSUserBundle/blob/50ab4d8fdfd324c1e722cb982e685abdc111be0b/Resources/views/ form.html.twig#L4

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

(对不起,我不得不拆分两个链接 b/c 我没有足够的声誉来发布两个以上的链接。伤心。)

于 2011-08-18T18:14:48.287 回答
3

在 symfony 2.7 中,使用choice_label参数,你可以像这样指定翻译域:

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

如果不指定域,则不会翻译选项。

于 2015-07-31T09:33:34.653 回答
0

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',
        ]
    );
于 2015-09-08T11:46:37.577 回答