- Add a language bar widget to your website
- Translate models
- Manage languages from database or configuration
- Message translation CRUD
composer require abcms/yii2-library:dev-master
composer require abcms/yii2-multilanguage:dev-master
$config = [
......
'language' => 'en',
'sourceLanguage' => 'en',
......
];
[
'components' => [
......
'multilanguage' => [
'class' => 'abcms\multilanguage\Multilanguage',
'languages' => [
'en' => 'English',
'ar' => 'Arabic',
'fr' => 'French',
],
],
],
]
Add the component to the bootstrap array to allow it to read and set the language from cookies and URL:
'bootstrap' => ['log', 'multilanguage'],
This URL manager class will automatically add the language to each URL.
'urlManager' => [
'class' => abcms\multilanguage\UrlManager::className(),
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<lang:([a-z]{2,3}(-[A-Z]{2})?)>/<controller>/<action>/' => '<controller>/<action>',
],
],
Using the language bar widget:
<?= abcms\multilanguage\widgets\LanguageBar::widget() ?>
or manually:
<a class="<?= (Yii::$app->language == 'en') ? 'active' : ''; ?>" href="<?= Url::current(['lang' => 'en']) ?>">En</a>
1- Add the migration namespaces in the console.php configuration:
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'abcms\library\migrations',
'abcms\multilanguage\migrations',
],
],
],
2- Run ./yii migrate
You can use abcms/yii2-generators to generate a custom model and CRUD or continue with the manual steps below.
Add the multi-language behavior and specify which attributes can be translated and the type for each field. If the field type is not specified, text input will be used by default.
[
'class' => \abcms\multilanguage\behaviors\ModelBehavior::className(),
'attributes' => [
'title',
'description:text-area',
],
],
Add in _form.php:
<?= \abcms\multilanguage\widgets\TranslationForm::widget(['model' => $model, 'form' => $form]) ?>
Add in view.php:
<?=
\abcms\multilanguage\widgets\TranslationView::widget([
'model' => $model,
])
?>
Add in Controller create and update actions:
$model->automaticTranslationSaving = true;
$translatedModel = $model->translate();
$translatedModels = Yii::$app->multilanguage->translateMultiple($models);