I'm having trouble into working with i18n in Yii2 advanced template.
Translation is not working!
I have run these commands in yii2 project root directory.
Official link
./yii message/config --languages=de,it,fr --messagePath=messages i18n.php
./yii message/extract i18n.php
It generate i18n.php under project root directory and de,it,fr directories under message directory.
in de directory I have create new file app.php with this content:
<?php
return [
'Home' => 'Home de',
'Getting Started' => 'Getting Started de',
];
In common/config/main.php
// set target language to be English
'language' => 'en-US',
// set source language to be English
'sourceLanguage' => 'en-US',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => realpath(dirname(__FILE__).'/../../').'messages',
//'sourceLanguage' => 'en-US',
//'fileMap' => [
//'app' => realpath(dirname(__FILE__).'/../../').'app.php',
// 'app/error' => 'error.php',
//],
],
],
],
]
View:
<?= Yii::t('app','Home')?>
<?= Yii::t('app','Getting Started') ?>
How I can get it working?
You can set target language in your config:
...
'language' => 'ru-RU',
...
If 'sourceLanguage' => 'en-US', yii will translate from en-US to ru-RU.
And config i18n component will be:
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/translation',
'fileMap' => [
'app' => 'app.php',
],
],
],
],
Directory structure is:
- translation
- ru-RU
- app.php
Example in file app.php
return [
'Home' => 'abcxyz',
'source key' => 'translate to russian',
];
Hope it helpful.
Goodluck and have fun!
If you are using advanced template,edit i18n.php
'sourcePath' =>__DIR__. DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
which will create message folder inside common folder.
And in config file
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
....
]
and in view use as you have.Good Luck
Related
I'm currently working on internationalization for a website using Yii2.
Usually, I use it like this:
Yii::t('frontend', 'Do you have something to eat?')
Then, I have two folders in common\messages called en-EN and id-ID. Each has frontend.php inside of it.
en-EN/frontend.php
return [
];
id-ID/frontend.php
return [
'Do you have something to eat?' => 'Ada yang bisa dimakan?'
];
It works fine, but I don't think it's practical because the sentence is too long and one character miss will not work.
So I tried using something like this:
Yii::t('frontend', 'My.Random.Sentence');
en-EN/frontend.php
return [
'My.Random.Sentence' => 'Do you have something to eat?',
];
id-ID/frontend.php
return [
'My.Random.Sentence' => 'Ada yang bisa dimakan?'
];
It only works for id-ID, but when I change back to english, it still displays My.Random.Sentence instead of Do you have something to eat.
This is my config in i18n.php
return [
'sourcePath' => __DIR__. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
'languages' => ['en-EN','id-ID'],
'translator' => 'Yii::t',
'sort' => false,
'removeUnused' => false,
'only' => ['*.php'],
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/vendor',
],
'format' => 'php',
'messagePath' => __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'messages',
'overwrite' => true,
];
And this is in frontend/config/main.php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en-US';
return [
// other options
'language' => $_SESSION['lang'],
'sourceLanguage' => 'en-EN',
'components' => [
'i18n' => [
'translations' => [
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
'backend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
],
],
],
//other options
];
Is this not possible? What is the correct way for my problem?
By default, i18n component doesn't translate the string when $sourceLanguage and $language are same. Instead it returns the source string.
But fortunately you can force it to translate the strings even when the $sourceLanguage and $language properties are same. To do that you need to set $forceTranslation property of MessageSource to true. You can do it in you frontend/config/main.php like this:
return [
// other options
'components' => [
'i18n' => [
'translations' => [
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'forceTranslation' => true,
],
// ...
],
],
],
//other options
];
If I add this configuration of the cms module to the config file
'cms' => [
'class' => 'yii2mod\cms\Module',
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => '',
'froalaEditorOptions' => [
'clientOptions' => [
'heightMin' => 300,
'theme' => 'dark',
'imageUploadURL' => 'upload-image',
'imageManagerDeleteURL' => 'delete-image',
'imageManagerDeleteMethod' => 'POST',
'imageManagerLoadURL' => 'images'
],
'excludedPlugins' => [
'file',
'emoticons'
]
],
'enableMarkdown' => false
]
It adds the default route of this module to all the routes like this
/cms/site/login /cms/site/index /cms/site/error. Why this is happening and how i can remove this?
If you want to remove the /cms module prefix by default, you can add a global route to backend/config/main.php(If you use advanced templates): '<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'.
for example:
// backend/config/main.php
return [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'
],
],
];
Access in your bowser: www.xxx.com/site/index, it is forwarded to: /cms/site/index
I install yii2-rbac following this site page: https://github.com/dektrium/yii2-rbac/blob/master/docs/installation.md .
I do it second time. First time I have done, but I wrote in the config/web.php file:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
I did not know, that 'rbac' => 'dektrium\rbac\RbacConsoleModule' it must write in the console.php (not in web.php).
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
],
`
This code I have wrote in both config files: web.php and console.php, but in the web.php I have wrote 'rbac' => 'dektrium\rbac\RbacConsoleModule' and in console.php I have not wrote it, but all worked: yii2-rbac has been installed succeful. And all transaction have passed succeful. But 'rbac' => 'dektrium\rbac\RbacConsoleModule' in web.php seems to me wrong. It isn't web module, it is console module. Then I have rollbacked transactions (migrate/down) and I have removed rbac at all by removing from composer.json "dektrium/yii2-rbac": "1.0.0-alpha#dev" declaration. All has been removed.
Than I began to install rbac second time. After composer installation I have wrote in the web.php:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
'rbac' => 'dektrium\rbac\RbacWebModule',
//'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
and in console.php I have wrote:
'modules' => [
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
The site on yii2 don't work after it!!! I have changed in the web.php "...RbacConsoleModule". Site works. Why it don't work with RbacWebModule? Then I tried to apply transactions, that I have rollbacked before, but raise error: You have wrong authManager configuration
enter image description here
What can I do? Help me. Ecscuse me for my English. I'm from Russia.
my console.php:
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
]
],
'modules' => [
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
//....
my web.php:
//This all in $component
'db' => require(__DIR__ . '/db.php'),
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
That all! The problem has been decided. It must write authManager section to modules, not in components:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
]
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
]
you need write that:
'components' => [
'authManager' => [
'class' => 'dektrium\rbac\components\DbManager',
'defaultRoles' => ['users'],
],
...
I installed yii2 and then added gii to yii2 from this link.
return [
'bootstrap' => ['gii'],
'modules' => [
'gii' => 'yii\gii\Module',
// ...
],
// ...
];
I want to plce this code in application configuration file where it is located?
Application configuration file reside in: project_name/config/web.php
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class'=>'yii\gii\Module',
'allowedIPs'=>['127.0.0.1','192.168.1.*'],
];
You will find a file web.php which is in in the config folder located at your root app folder, the file will contain something like the following:
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'name' => 'My Cool App',//If this line exists change it to your new app name otherwise add it.
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '_4wmrZYaMY7joBAFHrXKpEIFvs9m9S_I',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if(YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Notice I've added a line: 'name' => 'My Cool App',
Hope this helps.
We've been working on a project with Yii2 Advanced App, with a custom bootstrap template. I've generated the crud using gii. All other CRUDs work fine. But the User crud displays Yii2 User Module not the CRUD.
I've gone through amnah's complete documentations and couldn't find any solutions in any other places either. I even tried Yii2 documentations and it wasn't any help either.
This is my backend config
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => 'sahasa/index',
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'request' => [
'baseUrl' => $baseUrl,
],
'user' => [
'class' => 'amnah\yii2\user\components\User',
],
// 'user' => [
// 'identityClass' => 'common\models\User',
// 'enableAutoLogin' => true,
// ],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
'modules' => [
'user' => [
'class' => 'amnah\yii2\user\Module',
// set custom module properties here ...
],
'debug' => [
'class' => 'yii\debug\Module',
],
],
];
This is what I get when I goto localhost/app/backend/web/index.php?r=user
I want it to display a CRUD similar to this
I'm stuck there. Without the CRUD it'll be difficult to manage the USERS.
Any help is appreciated.
Thanks in advance.
I think you need to redefine the controller too. You need a new controller derived form the original controller for correctly addressing the new CRUD element.
I suppose your controller is in backend and is named user otherwise change properly the following example (part of config/main.php):
'user' => [
...
'controllerMap' => [
'user' => 'backend\controllers\user',
],
],
You can add this code to Controller in backend
public function init()
{
$user_id = Yii::$app->getUser()->id;
if($user_id){
$user = \amnah\yii2\user\models\User::findOne($user_id);
if ($user->can("admin")) {
// do something
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
parent::init();
}
Just click the link /user/admin
You'll get CRUD for users.