Symfony:如何设置实体约束注释的转换域

时间:2018-01-16 19:24:30

标签: symfony

在Symfony中,可以通过以下注释指定实体约束:

 /**
 * @Assert\NotBlank(message="author.name.not_blank")
 */
protected $name;

默认翻译域为validators。 我想知道如何指定其他翻译域而不是默认的翻译域,只有一组这样的验证。

2 个答案:

答案 0 :(得分:1)

简短的回答是默认情况下你不能,因为没有translation_domain选项可以直接在实体约束Annotation中设置它,除非你有一个非常特殊的用例有很多工作要做,以实现自己错过的选项。

如果您查看Symfony Validator Component的源代码,您会看到默认翻译域由ExecutionContextFactory设置。然后,所有约束验证器都会继承上下文,因此您只能在验证器本身内更改它,更准确地说,在validate方法中,您必须在每个验证器中实现它,就像在NotBlankValidator中一样。 :

public function validate($value, Constraint $constraint)
{
    if (!$constraint instanceof NotBlank) {
        throw new UnexpectedTypeException($constraint, 
        __NAMESPACE__.'\NotBlank');
    }
    if (false === $value || (empty($value) && '0' != $value)) {
        $this->context->buildViolation($constraint->message)
            ->setParameter('{{ value }}', $this->formatValue($value))
            ->setCode(NotBlank::IS_BLANK_ERROR)
            ->setTranslationDomain('your_trans_domain') #<--- THIS LINE
            ->addViolation();
    }
}

因此,最简单的选项(特别是如果您只需要一些验证器)就是构建您的own validators,以便像上一个示例一样设置翻译域。

如果你需要为第三方验证器更改它,只需构建自己的验证器并为第三部分验证器添加服务别名:

App\NotBlankValidator:
    tags: [validator.constraint_validator]
    alias: The\Third\Part\Validator\Namespace

无论如何,知道您可以为所有验证器全局更改翻译域,这无论如何都是有用的。

Symfony&lt; = 3.3(如果您不使用Flex,则为3.4)

config.yml文件(config文件夹内):

framework:
    validation: { translation_domain: your_custom_trans_domain_string }

Symfony&gt; 3.4(如果使用Flex,也是3.4)

framework.yaml文件(config/packages文件夹内):

framework:
    validation: { translation_domain: your_custom_trans_domain_string }

答案 1 :(得分:0)

Create a validators catalog file in the translations/ directory:


`<!-- translations/validators.en.xlf -->
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="author.name.not_blank">
                <source>author.name.not_blank</source>
                <target>Please enter an author name.</target>
            </trans-unit>
        </body>
    </file>
</xliff>`