1

我有现在的情况

<?php

namespace MyBundle\Form\Type;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

class MyFormType extends AbstractType implements ContainerAwareInterface
{
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $translator = $this->container->get('translator');

        $builder->add('my-field', 'text', [
            'constraints' => [
                new Assert\NotBlank([
                    'message' => $translator->trans('%field% should not be blank.', ['%field%' => $translator->trans('MyFieldName')]),
                ]),
            ],
        ]);
    }

    public function getName()
    {
        return 'my_form';
    }
}

这个例子已经有效,我正在尝试重构它,所以我不必在其中包含容器(或翻译器)。

挑战在于保持

  • '%field% 不应为空。' 和
  • '我的字段名'

作为仅有的两个可翻译字符串,'因为 MyFieldName 很可能已经被翻译(如标签),留下 '%field% 不应为空。作为适用于站点中任何字段的通用消息。

4

2 回答 2

0

如果您通过取消注释此行来激活symfony 框架配置中的翻译器:

#translator: { fallbacks: [%locale%] }

在 中,默认情况下,验证器设置的所有违规错误消息都使用域中config.yml的值进行转换。validators

您应该使用我们app/Resources/translations/validators.(_format)src/(Acme/)*Bundle/Resources/translations/validators.(_format)定义您的自定义消息,并在完成后清除您的缓存。

例子 :

# app/Resources/translations/validators.yml
my_form:
    errors:
       my_field:
           not_blank: My field should not be blank

// FormType
$builder->add('my-field', 'text', [
        'constraints' => [
            new Assert\NotBlank([
                'message' => 'my_form.errors.my_field.not_blank',
            ]),
        ],
    ]);

来自验证器的错误消息将被自动翻译。

请参阅http://symfony.com/doc/current/book/translation.html#translating-constraint-messages

于 2016-02-10T23:38:34.570 回答
0

过去进入约束 'attr' => array('placeholder' => 'Message', )

于 2016-02-10T16:59:35.417 回答