We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Translating flash and model messages

I am using translations as shown on https://docs.phalcon.io/en/latest/reference/translate.html, but i have two questions.

  1. How do I translate $this->flashSession-> messages?
  2. How do I translate validation messages from a model?


26.3k

I have decided to use gettext to perform translations. There is a gettext adapter in the incubator. It is already implemented in Phalcon 1.3.2 version but there is no docs at the moment - as far as I know.



174

I am use gettext, all code in bootstrap or index.php

<?php

$config = new \Phalcon\Config([
    'app' => [
        'base'          => '/',
        'debug'         => (bool) ($_SERVER['REMOTE_ADDR'] == '127.0.0.1'),
        'locale'        => 'es_ES',
    ],
    'path' => [
        'controllers'   => __DIR__.'/../app/controllers/',
        'libraries'     => __DIR__.'/../app/libraries/',
        'messages'      => __DIR__.'/../app/messages/',
        'models'        => __DIR__.'/../app/models/',
        'views'         => __DIR__.'/../app/views/',
        'tmp'           => __DIR__.'/../tmp/',
    ],
]);

$di->set('view', function() use ($config) {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir($config->path->views);
    $view->registerEngines(['.phtml' => function($view, $di) use ($config) {
        $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
        $volt->setOptions([
            'compiledPath'  => $config->path->tmp,
            'compileAlways' => $config->app->debug,
        ]);
        $volt->getCompiler()->addFunction('_', 'gettext');
        return $volt;
    }]);
    return $view;
}, true);

putenv('LANG='.$config->app->locale);
setlocale(LC_ALL, $config->app->locale.'.utf8');
bindtextdomain('messages', $config->path->messages);
bind_textdomain_codeset('messages', 'utf8');
textdomain('messages');

For each language I need the following structure:

app -> messages -> es_ES -> LC_MESSAGES -> messages.po

The messages.po file contains the translated strings, created and updated with poedit for example.

For simplicity of gettext scanner I have mapped the function _ () to volt.

In a controller: $this->flash->error(_('Bad credentials.'));

In a volt view: {{ _('Homepage') }}

Best regards. --cesar