- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
Yii2 Multilingual & Localization Support
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.
1. Understanding Yii2 Localization & Internationalization
Yii2 follows Internationalization (i18n) and Localization (L10n) principles:
- Internationalization (i18n) – Making the application adaptable to different languages.
- Localization (L10n) – Translating content, dates, numbers, and messages to match the user's locale.
Yii2 provides built-in tools for message translation, date formatting, and language switching.
2. Configuring Yii2 for Multilingual Support
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.
3. File-Based Translations in Yii2
3.1 Creating Message Files
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.php
Each file returns an array of translated strings.
Example: messages/en/app.php
return [
'Hello' => 'Hello',
'Welcome' => 'Welcome to our website',
'Login' => 'Login',
];
Example: messages/fr/app.php
return [
'Hello' => 'Bonjour',
'Welcome' => 'Bienvenue sur notre site',
'Login' => 'Connexion',
];
3.2 Using Translations in Views & Controllers
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:
Bonjour
If no translation is found, Yii2 will fallback to sourceLanguage
.
4. Database-Driven Translations in Yii2
Instead of using message files, we can store translations in the database, making it easier to manage.
4.1 Create a Translation Table
Run the following migration:
php yii migrate/create create_translation_table
Then, 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 migrate
4.2 Insert Translations into the Database
Insert 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');
4.3 Implement Database Translation Component
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);
}
}
4.4 Register the Component in config/web.php
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'app\components\DbMessageSource',
],
],
],
],
4.5 Using Database Translations in Views
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.
5. Switching Languages in Yii2
Allow users to switch languages dynamically by storing their preference in a session or cookie.
5.1 Create a Language Switcher in the Layout
<?= Html::a('English', ['site/change-language', 'lang' => 'en']) ?>
<?= Html::a('Français', ['site/change-language', 'lang' => 'fr']) ?>
5.2 Create the change-language
Action in SiteController.php
public function actionChangeLanguage($lang)
{
Yii::$app->session->set('language', $lang);
Yii::$app->language = $lang;
return $this->redirect(Yii::$app->request->referrer);
}
5.3 Apply the Language in config/bootstrap.php
Create 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.
6. Formatting Dates & Numbers Based on Locale
Yii2 provides the Formatter
component to format dates, numbers, and currencies according to the user's locale.
6.1 Enable Formatter in config/web.php
'components' => [
'formatter' => [
'class' => 'yii\i18n\Formatter',
'defaultTimeZone' => 'Asia/Calcutta',
'locale' => Yii::$app->language, // Use dynamic language
],
],
6.2 Format Dates, Numbers & Currencies in Views
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.
Conclusion
Yii2 provides flexible multilingual and localization features.
- File-based translations – Simple and fast for small apps
- Database-driven translations – Scalable and ideal for large apps
- Language switching – Store user preferences using session or cookies
- Date & number formatting – Auto-formats based on the locale
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Grow your business with Facebook Marketing
- How to Start Your Career as a DevOps Engineer
- How to Become a Good Data Scientist ?
- Extract RGB Color From a Image Using CV2
- Datasets for Natural Language Processing
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Store Data Into CSV File Using Python Tkinter GUI Library
- Datasets for Speech Recognition Analysis
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- The Ultimate Guide to Starting a Career in Computer Vision
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Top 10 Blogs of Digital Marketing you Must Follow
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- SQL Joins Explained: A Complete Guide with Examples
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset