Yii2 - Multi language - php

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',

Related

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) ..

Yii DbMessageSource App* Error

I am currently building a second system with yii2. It will use some tables from a Yii1 database for translation. The Yii1 project was originally translated using files but this has now been moved to the db. All the translations of the Yii1 system use one of three categories app,flash,email of which the vast majority use app.
In the Yii2 project I have the following in the web.php config file.
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'cdb',
'sourceMessageTable' => 'translation_source',
'messageTable' => 'translation',
'forceTranslation'=>true,
],
],
],
All of the translations on the system that use app are not translated, however, all other categories are. If I change the above code to
'i18n' => [
'translations' => [
'app*' => [
Then I get an error for other categories but not app and the app strings are translated as expected. The error I get is
Unable to locate message source for category 'flash'.
If however I change my config to the following, this works for all translations.
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'cdb',
'sourceMessageTable' => 'translation_source',
'messageTable' => 'translation',
'forceTranslation' => true,
],
'app*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'cdb',
'sourceMessageTable'=>'translation_source',
'messageTable' => 'translation',
'forceTranslation' => true,
],
],
],
It just seems odd that I am having to include effectively the same code block twice. Can anyone tell me how I can achieve this in one array or is this the expected behaviour?
** Update **
I do see some mention of * in the docs Docs. I also see some mention of this in the Forum

Yii2 API routing with versions

I'm having a problem getting my Yii2 application API setup. We have a website up and running and I've been tasked to setup a API for 3rd parties to connect to us to perform certain function calls. I've been reading the docs and did some googling and found this site that has a base setup for website and api. I installed it to see how it was setup, so I could try and apply it to my site.
I'm hitting the API section of the directory structure just fine, but I can't for the life of me figure out how the routing is supposed to work.
My directory structure is now as follows:
root
--api
----config
------main.php
----modules
------v1
--------controllers
----------SearchController.php
--------models
----------Search.php
----------ApiUser.php
--------Module.php
----runtime
----web
------assets
--assets
--commands
--config
---common
---site1
--controllers
----base
----common
----site1
--mail
--migrations
--models
--modules
--runtime
--vendor
----vendor_dirs
--views
--web
My apache config is as follows for the api alias:
Alias /api /var/www/website.com/api/web
<Directory "/var/www/webiste.com/api/web">
AllowOverride All
</Directory>
I'm confused to as to how I'm supposed to setup the url_manager section of the config file so that www.website.com/api/v1/search/do-search will hit the \api\modules\v1\controllers\SearchController::actionDoSearch() function.
My config looks as follows
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module',
'controllerNamespace' => 'api\modules\v1\controllers',
],
],
'components' => [
'user' => [
'identityClass' => 'api\v1\models\ApiUser',
'enableAutoLogin' => false,
'enableSession' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info', 'trace'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/search',
'pluralize' => false,
'extraPatterns' => [
'GET do-search' => 'do-search'
]
],
],
],
],
I've read through the routing guide on the Yii2 website, but it didn't really shed any light on the subject.
update
So after tweaking my config, I think I managed to make some headway, but I'm still not there yet.
I'm now getting the following error:
ReflectionException
Class api\modules\v1\Module does not exist
My namespace in the module is as follows:
namespace api\modules\v1;
class ApiModule extends \yii\base\Module
{
So it seems that the namespace is not registering property, or the base path for the module is not correct.
Any help explaining things, so I can better understand would be greatly appreciated.
Thanks
SUCCESS
I'm an idiot. The Module.php file was not in the v1 directory, but actually one directory down.
Add your module to modules section:
'modules' => [
'v1' => [
'class' => 'app\modules\v1\Module',
'basePath' => '#app/modules/v1',
'controllerNamespace' => 'app\modules\v1\controllers'
]
Add url rules for REST controller:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/search']
],
'GET v1/search/do-search' => 'v1/search/do-search',//actually should work without this line
When creating new controller add it to controller section in url rules.

Yii2 translation does not work

I have Yii2 advanced template, I want to set translation for my frontend views, here is what I did:
frontend/config/main.php:
'sourceLanguage'=>'en-US',
'language'=>'en-US',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
]
then I added i18n.php in common/config:
<?php
return [
'sourcePath' => __DIR__. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
'languages' => ['fr-FR','en-US'], //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' => __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'messages',
'overwrite' => true,
];
and the common/messages/en-US/app.php:
<?php
return[
// Menu texts
'menu.login'=>'login',
];
and I used it in the views as : Yii::t('app', 'menu.login');
but the translation didn't work, it displayed as menu.login
You Just Follow This Steps......
Step 1: In the common directory , create messages folder.
Step 2: Create i18n.php file inside common/config directory with following content:
<?php
return [
'sourcePath' => __DIR__. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
'languages' => ['en-EN', 'ru-RU'], //Add languages to the array for the language files to be generated, here are English and Russian.
'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', //path of messages folder created above
'overwrite' => true,
];
Note: Make sure to add all required languages to 'languages' array. In the above example I have added English and Russian for Generate Yii2 Framework multi language.
Step 3: Add the i18n component in config file common/main.php configuration as follows:
'components' => [
...
'i18n' => [
'translations' => [
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
'backend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
],
],
],
...
],
Step 4:
Add the language module in common config file to use the default language on your app, such as:
'language' => 'en-EN' inside common/main.php.
You now can use Yii::$app->language = ‘en-EN’ at any runtime like URL request, query code.
Note: In any Model, Controller Generate by Gii, you can see Enable I18n ticket choice, just enable this for Multi language. Gii Tool will auto generate a Model has pre-defined as below, due to frontent or backend folder:
Yii::t('frontend', 'Translatable String');
Yii::t('backend', 'Translatable String');
Step 5: Run this command line from Yii2 app folder:
yii message/extract #common/config/i18n.php
This command line will Generate Yii2 Framework multi language translation files inside common/messages and divide into frontend and backend folder.
For example: Yii message will generate the translation files as follows:
common/
.....
messages/
en-EN/
backend.php
frontend.php
ru-RU/
backend.php
frontend.php
.....
If you want to edit the translate text, just open backend.php or frontend.php file and edit.

Not working Translations with Environments in Yii2

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.

Categories