【问题标题】:Translating validation error messages in a custom FormType翻译自定义 FormType 中的验证错误消息
【发布时间】:2016-02-10 16:48:58
【问题描述】:

我有现在的情况

<?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% 不应为空。作为适用于站点中任何字段的通用消息。

【问题讨论】:

  • 从标题中删除了“占位符”,因为人们似乎对此感到困惑。

标签: forms symfony localization symfony-forms symfony-validator


【解决方案1】:

过去的约束 'attr' => 数组( '占位符' => '消息', )

【讨论】:

【解决方案2】:

如果您在 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

【讨论】:

  • 是的,他们会的,但这不是我要问的。我要问的是是否可以在上面的示例中执行我 am 所做的事情,而无需在表单类中使用翻译器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2014-04-02
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多