Zf2 Translation Validator with Text Domain

264 Views Asked by At

i have an problem within the translator. I want to use for every module an module specific text domain (NAMESPACE). First i've seen that ZF2 need to inject the Translator into the Validators since Version 2.2 so i've do somethink like this in my Application\Module.php

class Module
{
    public function onBootstrap(\Zend\Mvc\MvcEvent $e)
    {
        $translator = new \Zend\Mvc\I18n\Translator(
            $e->getApplication()->getServiceManager()->get('translator')
        );

        \Zend\Validator\AbstractValidator::setDefaultTranslator($translator);
    }
}

This works to inject the default Translator. So now i've need to set the TextDomain for the Validators. At the time i set them via an Validator Factory for every Module Validator like

Class PasswordFactory implements FactoryInterface
{
    public function CreateServcie(ServiceLocatorInterface $sl) {
        $validator = new PasswordValidator();
        $validator->setTranslatorTextDomain('User'); // User = Module namespace
    }
}

This works but its a little bit tedious and bloats the code. So is there an easy way to handle TextDomains for Validators? For example attach them within the Event:Dispatch or via Initializer?

regards

1

There are 1 best solutions below

10
newage On

You can set default TextDomain in Module

class Module
{
    public function onBootstrap(\Zend\Mvc\MvcEvent $e)
    {
        ...
        \Zend\Validator\AbstractValidator::setDefaultTranslatorTextDomain(__NAMESPACE__);

Yes it's not work, because NAMESPACE get local NAMESPACE

For get current __NAMESPACE__ you can use MvcEvent::EVENT_DISPATCH action.

public function onBootstrap(MvcEvent $e)
{
    ...
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'setTextDomain'), 100);
}

public function setTextDomain(MvcEvent $e)
{
    $currentNameSpace = $e->getRouteMatch()->getParam('__NAMESPACE__');
    \Zend\Validator\AbstractValidator::setDefaultTranslatorTextDomain(currentNameSpace);
}