How to use translate helper in controllers in zend framework 2

Sanju picture Sanju · Jan 9, 2013 · Viewed 12.4k times · Source

Is there any possible way to translate strings in controllers instead of view?

Right now, in my controllers, if I pass strings like :

public function indexAction() {
    return array('message' => 'example message');
}

It will be translated in index.phtml

<?php print $this->translate($message);?>

It works well, but poeditor unable to find strings from controller files

Guess it would be cool if I can use something like :

public function indexAction() {
    return array('message' => $view->translate('example message'));
}

in controllers

Thanks in advance for help

Answer

webcoder picture webcoder · Jan 9, 2013

To use view helper in controller, you can use 'getServiceLocator'

$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('helperName');

Either you can use php getText function ___('my custom message') and add "_" as sources keyword in poedit (in catalog properties) so poedit will filter strings from controller. eg:

array('message' => _('my custom message'));

And as per your code, you can use helper directly like this

$translate = $this->getServiceLocator()->get('ViewHelperManager')->get('translate');

array('message' => $translate('my custom message'));