Zend framework 3 - Translate validation message

倖福魔咒の 提交于 2021-01-29 18:32:26

问题


I need to translate validation message.

I found this link

https://zendframework.github.io/zend-validator/messages/

In my global config I have this

'translator' => [
        'locale' => ['it_IT','en_US'],
        'translation_file_patterns' => [
            [
                'type'     => 'gettext',
                'base_dir' => getcwd() .  '/data/language',
                'pattern'  => '%s.mo',
            ],
        ],
    ],

In the view translator , using __('key'), work fine. But validation message remain in english

I used the site's guide to validate the form this is my code

<?php

namespace Admin\Model;

// Add the following import statements:
use DomainException;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\NotEmpty;
use Zend\Validator\StringLength;

class LoginModel implements InputFilterAwareInterface
{
    public $username;
    public $user2;

    private $inputFilter;

    .....

    public function getInputFilter()
    {
        if ($this->inputFilter) {
            return $this->inputFilter;
        }

        $inputFilter = new InputFilter();

        $inputFilter->add([
            'name' => 'username',
            'required' => true,
            'validators' => [
                [
                    'name' => NotEmpty::class
                ],
            ],
        ]);

        $inputFilter->add([
            'name' => 'user2',
            'required' => true,
            'validators' => [
                [
                    'name' => NotEmpty::class,
                ],
            ],
        ]);

        $this->inputFilter = $inputFilter;
        return $this->inputFilter;
    }
}

Where I put the code of the link above?

Answer to comment

I readed a zend i18n validator doc. But I don't understand where put this code. I've more form to validate

$translator = new Zend\Mvc\I18n\Translator();
$translator->addTranslationFilePattern(
    'phpArray',
    Resources::getBasePath(),
    Resources::getPatternForValidator()
);

AbstractValidator::setDefaultTranslator($translator);

回答1:


You can add the messages in the options of a validator. Like so:

$inputFilter->add([
    'name' => 'user2',
    'required' => true,
    'validators' => [
        [
            'name' => NotEmpty::class,
            'options' => [
                'messages' => [
                    'messageKey'  => 'non-translated message',
                    'messageKey2' => _('translated message'),
                ],
            ],
        ],
    ],
]);

To overwrite the message of Zend, you might wish to use the constants used in the Validators instead. E.g. your question uses the NotEmpty validator. If you have a look at that class, you'll find:

/**
 * @var array
 */
protected $messageTemplates = [
    self::IS_EMPTY => "Value is required and can't be empty",
    self::INVALID  => "Invalid type given. String, integer, float, boolean or array expected",
];

So, when you define custom messages like I've shown above, you'd best do:

'messages' => [
    NotEmpty::IS_EMPTY => 'non-translated message',
    NotEmpty::INVALID  => _('translated message'),
],

Please note: You do not need to translate all of ZF's default messages, unless the language you want is not supported, of course. More info

zend-validator is shipped with more than 45 different validators with more than 200 failure messages. It can be a tedious task to translate all of these messages. For your convenience, pre-translated messages are provided in the zendframework/zend-i18n-resources package

Supported languages of that repo here


Additional question added to question of where to place config to enable translator + translations

To make sure that the translator knows where to find translation files, add the following to each module in the module.config.php:

'translator'      => [
    'translation_file_patterns' => [
        [
            'type'     => 'gettext',                // This uses the php-gettext module
            'base_dir' => __DIR__ . '/../language', // Where the folder with files is in relation to this config file
            'pattern'  => '%s.mo',                  // Update extension for what you use
        ],
    ],
],

For this to be used you must have a Translator package installed. I would recommend you use the Zend Mvc i18n package.

Enable it in your config/modules.config.php file by adding the namespace to the module array: 'Zend\\Mvc\\I18n',

Add and install the module via the composer.json by adding it to your require list. Current version at time of writing included:

"zendframework/zend-mvc-i18n": "^1.1"

To make sure it'll work in the future, it's a good idea to add these to the require as well:

"ext-intl":"*",
"ext-gettext":"*",

The above will require that the intl and gettext PHP Modules are installed in the currently running PHP instance.


Below a simple look at setup for module file/folder structure




回答2:


Ok i found solution to problem especially thanks to the support of Rkeet(thanks).

The documentation have some imprecision.

This row

$translator = new Zend\Mvc\I18n\Translator();

generates an error because constructor require parameter. I did change the row in this way:

$translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');

Then i realize that translator search in this directory

vendor\zendframework\zend-i18n-resources\src/../languages/

for locale it_IT

In that path there isn't it_IT folder but only "it". I did rename it and all work fine.

Below complete code of my Module.php file

<?php


namespace Admin;

use Zend\I18n\Translator\Resources;
use Zend\Validator\AbstractValidator;
use Zend\Mvc\MvcEvent;


class Module
{
    const VERSION = '3.0.3-dev';

    public function onBootstrap(MvcEvent $e)
    {
        /** @var \Zend\Mvc\I18n\Translator $translator */
        $translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
        $translator->addTranslationFilePattern(
            'phpArray',
            Resources::getBasePath(),
            Resources::getPatternForValidator()
        );
        AbstractValidator::setDefaultTranslator($translator);
    }

    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }
}



回答3:


If you want to use default ZF3 translations for validation message you have to modify the "Module.php" file under "src" folder.

First of all install the "zend-mvc-i18n" module via composer using "require" command:

composer require zendframework/zend-mvc-i18n

Then use this code in "Module.php" for example to view validation message in italian language:

    <?php

    namespace Application;

    use Zend\I18n\Translator\Resources;
    use Zend\Mvc\I18n\Translator;
    use Zend\I18n\Translator\Translator as I18nTranslator;
    use Zend\Validator\AbstractValidator;
    use Zend\Mvc\MvcEvent;
    use Zend\Mvc\ModuleRouteListener;

    class Module
    {
        const VERSION = '3.0.3-dev';

        public function onBootstrap(MvcEvent $e)
        {
            $eventManager = $e->getApplication()->getEventManager();
            $moduleRouteListener = new ModuleRouteListener();
            $moduleRouteListener->attach($eventManager);
            $t = new I18nTranslator();
            $t->setLocale('it_IT');
            $translator = new Translator($t);
            $translator->addTranslationFile('phpArray', 'vendor/zendframework/zend-i18n-resources/languages/it/Zend_Validate.php', 'default', 'it_IT');
            AbstractValidator::setDefaultTranslator($translator);
        }
     }

You can change "it_IT" to "es_ES" or "de_DE" to view validation message in other languages.



来源:https://stackoverflow.com/questions/52458738/zend-framework-3-translate-validation-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!