Yii2 provides robust support for multilingual applications and localization, allowing you to translate UI content, dates, numbers, and messages into different languages. In this tutorial, we will cover both file-based translations and database-driven translations to make your application support multiple languages efficiently.
Yii2 follows Internationalization (i18n) and Localization (L10n) principles:
Yii2 provides built-in tools for message translation, date formatting, and language switching.
First, enable multilingual support by defining supported languages in config/web.php:
'language' => 'en-US', // Default language
'sourceLanguage' => 'en-US', // Original language of messages
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource', // File-based translations
'basePath' => '@app/messages',
],
],
],
],Here, we set:
language – The default language (en-US).sourceLanguage – The language of untranslated messages.i18n component – Handles message translation.Yii2 stores translations in PHP message files inside the messages/ directory.
For example, create a folder structure like this:
/messages
/en
app.php
/fr
app.phpEach file returns an array of translated strings.
messages/en/app.phpreturn [
'Hello' => 'Hello',
'Welcome' => 'Welcome to our website',
'Login' => 'Login',
];messages/fr/app.phpreturn [
'Hello' => 'Bonjour',
'Welcome' => 'Bienvenue sur notre site',
'Login' => 'Connexion',
];To display a translated message, use:
echo Yii::t('app', 'Hello'); If the user switches to French (fr), Yii2 will automatically load messages/fr/app.php, and the output will be:
BonjourIf no translation is found, Yii2 will fallback to sourceLanguage.
Instead of using message files, we can store translations in the database, making it easier to manage.
Run the following migration:
php yii migrate/create create_translation_tableThen, define the table in migrations/m220101_000000_create_translation_table.php:
use yii\db\Migration;
class m220101_000000_create_translation_table extends Migration
{
public function safeUp()
{
$this->createTable('{{%translation}}', [
'id' => $this->primaryKey(),
'category' => $this->string()->notNull(),
'message' => $this->string()->notNull(),
'language' => $this->string(10)->notNull(),
'translation' => $this->text()->notNull(),
]);
}
public function safeDown()
{
$this->dropTable('{{%translation}}');
}
}Run the migration:
php yii migrateInsert some translations manually into the database:
INSERT INTO translation (category, message, language, translation)
VALUES ('app', 'Hello', 'fr', 'Bonjour');
INSERT INTO translation (category, message, language, translation)
VALUES ('app', 'Welcome', 'fr', 'Bienvenue sur notre site');Create a custom translation component in components/DbMessageSource.php:
namespace app\components;
use yii\i18n\MessageSource;
use Yii;
class DbMessageSource extends MessageSource
{
protected function loadMessages($category, $language)
{
return Yii::$app->db->createCommand('SELECT message, translation FROM translation WHERE category=:category AND language=:language')
->bindValues([':category' => $category, ':language' => $language])
->queryAll(\PDO::FETCH_KEY_PAIR);
}
}config/web.php'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'app\components\DbMessageSource',
],
],
],
],Now, you can call translations in the same way:
echo Yii::t('app', 'Hello');Yii2 will now fetch the translations from the database instead of files.
Allow users to switch languages dynamically by storing their preference in a session or cookie.
<?= Html::a('English', ['site/change-language', 'lang' => 'en']) ?>
<?= Html::a('Français', ['site/change-language', 'lang' => 'fr']) ?>change-language Action in SiteController.phppublic function actionChangeLanguage($lang)
{
Yii::$app->session->set('language', $lang);
Yii::$app->language = $lang;
return $this->redirect(Yii::$app->request->referrer);
}config/bootstrap.phpCreate a config/bootstrap.php file:
if (Yii::$app->session->has('language')) {
Yii::$app->language = Yii::$app->session->get('language');
}Register this file in config/web.php:
'bootstrap' => ['config/bootstrap.php'],Now, the application will remember the user's selected language.
Yii2 provides the Formatter component to format dates, numbers, and currencies according to the user's locale.
config/web.php'components' => [
'formatter' => [
'class' => 'yii\i18n\Formatter',
'defaultTimeZone' => 'Asia/Calcutta',
'locale' => Yii::$app->language, // Use dynamic language
],
],echo Yii::$app->formatter->asDate('2024-01-01'); // 01 January 2024
echo Yii::$app->formatter->asCurrency(100, 'INR'); // ₹100.00
echo Yii::$app->formatter->asPercent(0.85); // 85%Yii2 will automatically format based on the selected language.
Yii2 provides flexible multilingual and localization features.
Sign in to join the discussion and post comments.
Sign in