Yii2: quick tip on overriding core translations

Requirement: use a local custom string for a core Yii2 message.

Since of course I didn’t want to  touch files into @vendor (which wouldn’t survive an upgrade, and are out of git control) I worked it out by customizing the i18n core component of Yii2.

Open up config/web.php (if you created the app from the basic template) and add the following into the components section:

        'i18n' => [
            'translations' => [
                'yii' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    'basePath' => '@app/messages'
                ],
                '*' => [
                    'class' => 'yii\i18n\PhpMessageSource'
                ],
            ],
        ],

This will tell Yii2 to look for yii category messages files into @app/messages.

Now in messages create the directories for the locales you want (in my case I just needed it for the Italian localization) and create a new php file for the category you need, yii in this case. Now add in the  newly created messages/it/yii.php the following content:

<?php 
/** 
  * Messages override for yii translation category 
  */ 
use yii\helpers\ArrayHelper; 
// We merge the upstream translations with our local array of strings 
return ArrayHelper::merge(require(Yii::getAlias("@vendor/yiisoft/yii2/messages/it/yii.php")), [ 
   // Custom messages 
   'Update' => 'Modifica',
]);

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.

Solve : *
2 + 30 =


Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.