Not working Translations with Environments in Yii2 - php

I have set 3 environments.
My app needs to load different sets of translations because each env is different.
I have the RO, HU, DE languages.
I am trying to set the translations, but it does not work.
in frontend/config main.php i have:
'sourceLanguage' => 'en',
'language' => 'en',
in the frontend/web/index.php i have:
defined('YII_ENV') or define('YII_ENV', 'dev_ro');
also, i am merging the config array:
(file_exists(__DIR__ . '/../../environments/' . YII_ENV . '/common/config/main-local.php') ? require(__DIR__ . '/../../environments/' . YII_ENV . '/common/config/main-local.php') : [])
now, in environments/dev_ro/common/config/, in components i have:
'i18n' => [
'translations' => [
'companie' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en',
'fileMap' => [
'companie' => 'companie.php',
],
],
],
],
in the Companie model i have:
'nume' => Yii::t('companie', 'Name'),
this is the movie, with my thing:
movie

The problem is in app*, because it's not app* category, this works:
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'fileMap' => [
'companie' => 'companie.php',
],
],
],
],
Or if you want write 'companie*' =>
If it is still not working, you did set incorrect path to translate files. By default it must be BasePath/messages/LanguageID/CategoryName.php.
If you want to use one file in backend and frontend you should create for example common alias in common config (advanced yii application) and set this alias in i18n config. This is full example:
Common config:
Yii::setAlias('#common', dirname(__DIR__));
return [
'language' => 'ru',
'sourceLanguage' => 'ru',
'components' => [
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'fileMap' => [
'companie' => 'companie.php',
],
....
In traslate file /common/messages/en-US/companie.php
<?php
return [
'string in russian' => 'string in english'
];
Check translate using this code:
\Yii::$app->language = 'en-US';
echo \Yii::t('companie', 'string in russian');

You can also try to replace dash with underscore in language code and folder name:
en-US >> en_US
Works for me.

Related

yii2 adding extra language

I tried many times to add extra language for yii2 basic template and I have been failing in all them, let me show you all my codes and could you please help me to fix my error, actually the site does not say any error, everything is working smoothly but the language is not being switched to another
-----config/web.php----
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
return [
// set target language to be Russian
'language' => 'ru-RU',
// set source language to be English
'sourceLanguage' => 'en-US',
];
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '#app/messages',
//'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'qwdqdq',
],
messages/ru-RU/app.php
<?php
return [
'welcome' => 'Добро пожаловать',
'log in' => 'Войти',
'This is a string to translate!' => 'Это строка для перевода'
//...
];
----------siteController.php-------
Class SiteController extends Controller
{
public function actionChangeLang($local)
{
$available_locales = [
'ru-RU',
'en-US'
];
if (!in_array($local, $available_locales)) {
throw new \yii\web\BadRequestHttpException();
}
\Yii::$app->language = $local;
retur
n $this->goBack();
}
view file----- site/index.php
In your config/web.php add 'on beforeAction' like fallowing
return [
'id' => 'basic',
// set target language to be Russian
'language' => 'ru-RU',
// set source language to be English
'sourceLanguage' => 'en-US',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
...
],
'params' => [
...
],
'on beforeAction' => function(){
// get language from cookie, session or db
// and set it to app language
Yii::$app->language = isset($_COOKIE['language'])?$_COOKIE['language']:Yii::$app->language;
}
];
In your SiteControler function actionChangeLang replace line
\Yii::$app->language = $local;
with
setcookie("language", $local);
Now you will be able to change your locale and keep it between requests.
In my example I used cookies but you also may use any type of storage to store your locale.

yii2 app on online server:Invalid Parameter – yii\base\InvalidParamException The view file does not exist

I uploaded YII2 advanced my web app to online server.
I have 2 tables(companies,employees) and generated CRUD for these 2 tables.In main menu navigation given to view of company.
the below code i given on backend/views/layouts/main.php for navigation.
$menuItems = [
['label' => 'HOME', 'url' => ['/site/index']],
['label' => 'COMPANIES', 'url' => ['/companies/index']]
['label' => 'EMPLOYEES', 'url' => ['/employee/index']],
];
It's worked properly on localhost. But in online getting this exception.
Invalid Parameter – yii\base\InvalidParamException The view file does
not exist:
/home/echosoft/public_html/echosoftware/backend/views/companies/index.php
The file is existing in that folder.Please help me to solve this issue. I am stuck with this for 3 days.
This is backend\config.php codes
$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')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
This may help.Thanks in advance.
try using
['label' => 'COMPANIES', 'url' => ['/companies/index']]
and if the localhost is windows and online server is unix/linux like be sure you have the proper case in the pathname filename
Windows in case insensitive in pathname unix is case sensitive
If in your backend\views you have the folder name with uppercase (backend\views\Companies) you should change with lower case (backend\views\companies) ..

Yii2 Moving folder mdm-admin of mdmsoft and xml view appeared

I'm using Yii2 to develop my web app. But when I using yii2-admin of mdmsoft with version 3 for prettyURL, I move folder of yii2-admin to modules folder, and change main.php like this:
'bootstrap' => [
'admin'
],
'authManager' => [
'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
],
'modules' => [
'rbac' => [
'class' => 'app\modules\rbac\Module',
'layout' => '#backend/views/layouts/admin',
'controllerMap' => [
'assignment' => [
'class' => 'app\modules\rbac\controllers\AssignmentController',
]
],
]
],
],
'as access' => [
'class' => 'mdm\admin\classes\AccessControl',
'allowActions' => [
'*',
]
],
But when I access mydomain/rbac/assignment or mydomain.com/rbac/route ,... it's just a xml view, nothing more?
How I can fix it?

Yii2 - Multi language

I'm trying to set up the website's frontend translation using the i18l thing. Here is my i18l.php file placed on frontend/config
<?php
return [
'sourcePath' => 'frontend',
'languages' => ['en-US', 'pt-BR'] , //Add languages to the array for the language files to be generated.
'translator' => 'Yii::t',
'sort' => false,
'removeUnused' => false,
'only' => ['*.php'],
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/vendor',
],
'format' => 'php',
'messagePath' => 'frontend' . DIRECTORY_SEPARATOR . 'translations',
'overwrite' => true,
];
and here my main.php also on frontend
(...)
'language' => 'en-US',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => 'frontend/translations',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
]
I'm using the <?= Yii::t('app', 'some string') ?> on the sites and layouts and when I run the command ./yii message/extract #frontend/config/i18n.php it creates to me a folder called 'translations' contain other two folders 'en-US' and 'pt-BR' both with app.php which i already had filled with some translations. But still, no translation happens when i change the language on the main.php as it should be (i think).
I would appreciate if someone could give me a hand on that.
Thanks.
Great post, with all the needed details.
I was struggling with the same things, but you did it quite well.
So, if you can run the command and it generates the file, then the sourcePath is correct.
If it doesn't display the translation messages at runtime, despite your setting changes, then, I presume the issue could be on your basePath:
Try using, on your basePath configuration, the following:
'basePath' => '#frontend/translations',

yii2 - urlmanager routing not working

Here i have used yii2 configuration with rules
<?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')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => require(__DIR__ . '/routes.php'),
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
And given below routes.php
<?php
use yii\web\UrlRule;
return array(
// REST routes for CRUD operations
'POST <controller:\w+>s' => '<controller>/create', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>s' => '<controller>/index',
'PUT api/<controller:\w+>/<id:\d+>' => '<controller>/update',// 'mode' => UrlRule::PARSING_ONLY will be implicit here
'DELETE api/<controller:\w+>/<id:\d+>' => '<controller>/delete', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>/<id:\d+>' => '<controller>/view',
// normal routes for CRUD operations
'<controller:\w+>s/create' => '<controller>/create',
'<controller:\w+>/<id:\d+>/<action:update|delete>' => '<controller>/<action>',
);
When i access local2host.com/advanced/backend/web/index.php/country/create - It's working fine
but when i access through local2host.com/advanced/backend/web/index.php/api/country/create
It's throwing 404 - not found error
Unable to resolve the request "api/country/create".
As per my requirement :
when i access this link local2host.com/advanced/backend/web/index.php/api/country/create
it should access "country" as controller and "create" as action
It seems you have modules. First you need to add your api module into your config file:
'modules' => [
'api'
],
Second, you need to add module into your rules like below:
'<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
'<module:\w+><controller:\w+>/<action:update|delete>/<id:\d+>' => '<module>/<controller>/<action>',
This is remarkable that, you may need to take care of other rules with module and have your own customized rules.

Categories