How to get additional Form error messages translated in ZF2?

I have a Form where I have to perform a validation after the basic form validation (extending/overriding the Form#isValid(...)). If this "post-validation validation" fails, I add an error message to the Form like this:

MyForm extends Form
{
    protected $errorMessages = [];
    public function isValid()
    {
        $isValidBasic = parent::isValid();
        $isValidAdditional = ...;

        if (! $isValidAdditional) {
            $this->addErrorMessage('my custom error message');
        }
        return $isValidBasic && $isValidAdditional;
    }
    public function addErrorMessage($message)
    {
        $this->errorMessages[] = $message;
        return $this;
    }
    public function getErrorMessages()
    {
        return $this->errorMessages;
    }
    public function getMessages($elementName = null)
    {
        if ($elementName) {
            $messages = parent::getMessages($elementName);
        } else {
            $messages = array_merge($this->getErrorMessages(), parent::getMessages($elementName));
        }
        return $messages;
    }
}

It works, but "my custom error message" is ignored by the "translator" and I also get the original error message displayed.

I've already add a new translation file

class Application\Module

namespace Application;
...
class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $translator = $e->getApplication()
            ->getServiceManager()
            ->get('translator');
        $translator->addTranslationFile('phpArray',
            './vendor/zendframework/zend-i18n-resources/languages/de/Zend_Validate.php');
        $translator->addTranslationFile('phpArray',
            './vendor/my/lib/src/i18n-resources/languages/de/Validate.php');
        AbstractValidator::setDefaultTranslator($translator);
    }
}

... and it also works. But in this case it doesn't.

How to get custom Form error messages translated in ZF2?

Answers


On my ZF2 website, I solved it adding the following method in my models and forms:

protected function _translate($msg)
{
    return $msg;
}

Don't ask me why it's working, but it works with only this, the error messages are translated.


Need Your Help

PHP: htaccess default variable

php apache url dynamic-url

I want to set a default variable for a query that comes at the end of a url

PHP how to return variable without echo

php function variables return

Im looking to return one or another string variable from my php function.