首页 > 解决方案 > Symfony 4 不会翻译验证器消息并且总是显示英文默认值

问题描述

嗨,我是法国人,我尝试使用 Symfony 4 翻译验证器消息/

private function validationAction($iban)
{
    $validator = Validation::createValidator();

    $ibanClient = $iban;
    $constraint = new Assert\Collection(array(
        'iban' => array(
            new Assert\NotBlank(array('message' => 'Champs obligatoire')),
            new Assert\Iban()
        ),
    ));

    return $errors = $validator->validate(
        array('iban' => $ibanClient),
        $constraint
    );
}

我安装了翻译系统使用

composer require symfony/translation

现在,如果我输入 $iban = "FR00" 这就是响应:

This is not a valid International Bank Account Number (IBAN).

我在里面看到

供应商/symfony/validator/Resources/translations/validators.fr.xlf

该文件已经存在,我已经配置了语言环境

配置/包/framework.yaml

framework:
secret: '%env(APP_SECRET)%'
default_locale: fr

而在

配置/服务.yaml

parameters:
locale: 'fr'

我试图在

翻译/验证器.fr.yml

但没有变化。请帮助我,谢谢

标签: phpsymfonysymfony4

解决方案


好的,这是我的有效代码:

/**
 * @Route("/admin/rib/add", name="rib_add", condition="request.isXmlHttpRequest()")
 */
public function rib_add(Request $request, ValidatorInterface $validator)
{
    try {
        $errors = $validator->validate(
            array('iban' => $request->get('')),
            new Assert\Collection(array(
                'iban' => array(
                    new Assert\NotBlank(),
                    new Assert\Iban(),
                    new Assert\Length(array('min' => 5)),
                ),
            )));
        if (count($errors) > 0) {
            throw new \Exception($errors[0]->getMessage());
        }

        return new JsonResponse([
            'success' => true,
            'message' => 'Ajout du RIB ok',
            'data'    => [],
        ]);
    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);
    }
}

推荐阅读