how to setup multiple language in yii2 in simple way - php

I am working on yii2 framework.This is new framework for me. I want to setup multiple language. I tried some way but didn't got success. Can anyone please suggest me simplest way ? What should i have to do ?
I am using this reference link
http://techisworld.com/working-with-multiple-languages-app-in-yii2-framework-using-i18n-system.html

1- For dynamic content (coming from database) I usually use this:
webvimark/multilanguage
It is very easy and isolated from your app DB tables structure and code, that gives flexibility in adding/removing languages at the long term.
2- For static content (words inside the markup) in frontend as an example:
add the lines in your frontend/config/main.php file,
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en_US',
'fileMap' => [
'app' => 'app.php'
],
],
],
],
Put you translation file app.php file inside /frontend/messages, as any Yii translation file it returns an array of translations in a key-value pairs.
Then you can translate your static content using:
Yii::t('app', 'text to be translated')

Related

Yii2 framework: How to change English default language to Spanish

I am using the Yii2 Framework and I am translating all texts of buttons, labels, messages, etc.
Then I read this article http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html that shows how to do it automatically but I don't understand it.
I want to translate to Spanish from Argentina: es-AR or at least to any Spanish.
So I think I need to change from en-US to es-AR but I would like to know which files should I change.
Also I am using the great Gii code generator where I can see a checkbox called Enable I18N.
I watched these files but I am not sure if I am looking the right files:
vendor/yiisoft/yii2/base/Application.php
vendor/yiisoft/yii2/i18n/I18N.php
common/config/main-local.php
Add language propery and i18n component in application config. For advanced application template in common/config/main.php
return [
'language' => 'es-AR',
...
'components' => [
...
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
],
],
],
...
],
]
Use Yii::t() for all user messages (model labels, views, error messages etc).
echo \Yii::t('app', 'Friend');
Create directory messages/es-AR. Create file app.php in this directory and add translations
return [
'Friend' => 'Amigo',
'Girl' => 'Сhica',
...
];
Try to look into the official documentation, it is best tutorial for you. http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html
Also, look at this answer yii2 basic multiple language
You can change default language by changing 'language' parameter of your main configuration file. Like this:
return
[
// set target language to be English
'language' => 'en-US',
]
Where instead 'en-US' you must to set needed locale code, e.g. 'es-AR'

Yii2 make a path alias from information stored in DB

Right now I'm trying to implement themming for my Yii2 based project.
How I see the thing now:
User chooses an application theme from the list on the settings
page in backend.
Using yii2-settings I'm saving all the
configuration data in DB (pretty easy).
In the application
bootstrap.php I'm creating new alias called #theme. Basically it
should lead us to a application theme base path (used in search
paths, assets manager, e.t.c.).
According to official
documentation, that's how I configured my view component:
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
An issue I have is with p.3. According to yii2-settings documentation that's how I supposed to read the settings:
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
But obviously, it's not working for me because of yii2-settings component didn't initialized yet when bootstrap.php is called. I've been trying to initialize it later in the init() method of my base controller, then adjust other aliases manually, but I feel that way being somewhat 'unclean', and also it still fails because of #theme alias is also used in asset file which is Yii2 starting to publish before calling the controller's init method.
So does anyone has any thoughts of how to do that 'hacking' the code as less as possible? I know I could just move configuration to some file, then read it manually before the application initialization, but it's still not the way I want to go.
Maybe there's some way to override some system component to set the alias after db component is loaded, but before view component configuration? Or Yii loads this components in a different order? Anyway. Any help would be appreciated!
You could try an Application Event in bootstrap:
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
});
OR in configuration file:
[
'on beforeRequest' => function ($event) {
// ...
},
]
From Yii 2 docs:
EVENT_BEFORE_REQUEST This event is triggered before an application
handles a request. The actual event name is beforeRequest.
When this event is triggered, the application instance has been
configured and initialized. So it is a good place to insert your
custom code via the event mechanism to intercept the request handling
process. For example, in the event handler, you may dynamically set
the yii\base\Application::$language property based on some parameters.
Here's the final solution:
config/bootstrap.php:
// Setting a temporary path for components configuration - will be changed later
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/"));
config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
],
'on beforeRequest' => function ($event) {
$theme = Yii::$app->settings->get('theme', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
},

Yii2 Multiple caching storage

Is it possible to use two or more caching storage in yii2 framework? I already setup a Memcache for my web app but I wanted also to use a FileCache since I will be dealing with a large chunk of data.
hope someone can help. Thanks!
You can set any cache. Just set it at config file.
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'memCache' => [
'class' => 'MEMCACHE CLASS HERE',
],
.... ANY cache you want ...
]
You can register multiple cache application components. The component named cache is used by default by many cache-dependent classes (e.g. yii\web\UrlManager).
Official link
'components' => [
'cache' => [
'class' => 'yii\caching\MemCache',
],
'fileCache' => [
'class' => 'yii\caching\FileCache',
]
]

Yii2 combining & compressing assets not working with groups of bundles

I'm having trouble understanding how combine&compress of Yii2 assets work. I read the section in the guide (http://www.yiiframework.com/doc-2.0/guide-structure-assets.html) still I cannot make it work or at least understand the very basics of this matter.
From the example given there I am not able to reproduce that and solve the following scenario.
AppAsset contains the main css/js for the application. Shared and essential code is supposed to be included here. This one depends on another file called ExternalAssets which in turn depends on YiiAsset, BootstrapAsset and so forth.
CheckoutAsset contains code only relevant to the checkout process. Should be included as well with the above because it add custom functionality but only relevant to this section. $depends on AppAsset.
ProductViewAsset is the same as above but related to the visualization of a given product.
The asset configuration is given:
'bundles' => [
'yii\web\JqueryAsset',
'rmrevin\yii\fontawesome\AssetBundle',
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
'yii\widgets\ActiveFormAsset',
'frontend\assets\ExternalAssets',
'frontend\assets\AppAsset',
],
'targets' => [
'app' => [
'class' => 'yii\web\AssetBundle',
'basePath' => '#webroot/assets',
'baseUrl' => '#web/assets',
'js' => 'js/app-{hash}.js',
'css' => 'css/app-{hash}.css',
'depends' => [ ],
],
]
At this point I'm able to compress everything that is supposed to be common (although it maybe possible to strip some unnecessary files) but in the pages that use the ProductViewAsset or the CheckoutAsset the files included there do not get compressed in the same fashion.
Maybe it is possible to compress everything to a single file in the checkout process (common data + checkout data) or maybe not due to caching reasons. Don't know if this is possible yet I am unable to make it work. This is as far as I got with this. I tried doing this because it seemed natural but I started having errors like this one PHP Notice 'yii\base\ErrorException' with message 'Undefined index: frontend\assets\ExternalAssets' when trying to make different asset bundle groups:
'targets' => [
'app' => [
'class' => 'yii\web\AssetBundle',
'basePath' => '#webroot/assets',
'baseUrl' => '#web/assets',
'js' => 'js/app-{hash}.js',
'css' => 'css/app-{hash}.css',
'depends' => [
// 'frontend\assets\ExternalAssets'
],
'checkout' => [
'class' => 'yii\web\AssetBundle',
'basePath' => '#webroot/assets',
'baseUrl' => '#web/assets',
'js' => 'js/checkout-{hash}.js',
'css' => 'css/checkout-{hash}.css',
'depends' => [
'frontend\assets\AppAssets'
],
],
Maybe I'm looking at the wrong approach here but I'm not able to quite figure out what is the best way of doing this. I think that compressing everything to a single file should work better than not combine&compress the files yet I think it is possible to optimize the combine&compression approach in this case.
Thanks!
I am not sure if i understand the question you are giving, this is what i interpret as your requirements.
Make a normal action in your site controller calling a view 'site/assets/'
public function actionAssets()
{
return $this->render('assets');
}
Arrange your view like this example -
<?php
use dmstr\web\AdminLteAsset;
use backend\assets\AppAsset;
use dosamigos\fileupload\FileUploadPlusAsset;
use dosamigos\fileupload\FileUploadAsset;
use dosamigos\gallery\GalleryAsset;
use dosamigos\fileupload\FileUploadUIAsset;
use dosamigos\gallery\DosamigosAsset;
use budyaga\cropper\assets\CropperAsset;
use kartik\base\Html5InputAsset;
use kartik\base\WidgetAsset;
use kartik\form\ActiveFormAsset;
use kartik\affix\AffixAsset;
use kartik\alert\AlertAsset;
use kartik\color\ColorInputAsset;
use kartik\date\DatePickerAsset;
use kartik\datetime\DateTimePickerAsset;
use kartik\depdrop\DepDropAsset;
use kartik\depdrop\DepDropExtAsset;
use kartik\file\FileInputThemeAsset;
use kartik\growl\GrowlAsset;
use kartik\base\AnimateAsset;
use kartik\select2\Select2Asset;
use kartik\sidenav\SideNavAsset;
use kartik\spinner\SpinnerAsset;
use kartik\switchinput\SwitchInputAsset;
use kartik\time\TimePickerAsset;
use kartik\touchspin\TouchSpinAsset;
use kartik\typeahead\TypeaheadAsset;
use kartik\grid\GridViewAsset;
use kartik\dialog\DialogAsset;
$view = $this;
AdminLteAsset::register($this);
AppAsset::register($this);
FileUploadPlusAsset::register($view);
FileUploadAsset::register($view);
GalleryAsset::register($view);
FileUploadUIAsset::register($view);
DosamigosAsset::register($view);
CropperAsset::register($view);
Html5InputAsset::register($view);
WidgetAsset::register($view);
ActiveFormAsset::register($view);
AffixAsset::register($this);
AlertAsset::register($view);
ColorInputAsset::register($view);
DatePickerAsset::register($view);
DateTimePickerAsset::register($view);
DepDropAsset::register($view);
DepDropExtAsset::register($view);
FileInputThemeAsset::register($view);
GrowlAsset::register($view);
AnimateAsset::register($view);
Select2Asset::register($view);
SideNavAsset::register($this);
SpinnerAsset::register($view);
SwitchInputAsset::register($view);
TimePickerAsset::register($view);
TouchSpinAsset::register($view);
TypeaheadAsset::register($view);
GridViewAsset::register($view);
DialogAsset::register($view);
?>
<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
<p>Done</p>
<?php $this->endBody() ?>
<?php $this->endPage() ?>
Then make sure to hit this link before you do a deployment to prod to recompile assets.

How to use custom templates in gii (using Yii 2)

I'm trying to find a way to use custom Gii templates for Yii 2, but looking at the missing documentation in the docs, I assume it's not possible yet?
Or am I missing something?
Copy ie. the crud generator templates from gii/generators/crud/templates to your application app/templates/mycrud.
Then define the templates in your config:
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'generators' => [
'crud' => [
'class' => 'yii\gii\generators\crud\Generator',
'templates' => ['mycrud' => '#app/templates/mycrud']
]
]
];
Until the documentation is finished you may also have a look at my Gii extension how to create a custom generator and templates.

Categories