Yii DbMessageSource App* Error - php

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

Related

can't view backend user admin pages using Yii2-usuario

I'm using Yii2-usuario for my user module.
I ran the migrations found in "first step" under the section "Creating the first Administrator during a migration", and only changed from new \Da\User\Model\User() to new \app\models\user\Model\User() like this
$user = new \app\models\user\Model\User([
'scenario' => 'create',
'email' => "admin#admin.com",
'firstname' => 'first',
'lastname' => 'last',
'password' => "verysecret" // >6 characters!
]);
it populated my tables correctly. But when i login to backend and try to view https://localhost/bla/backend/web/user/admin/index, i get a 403 forbidden error
in my backend main.php i have this
'components' => [
....
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'enableRegistration' => false,
'maxPasswordAge' => 90,
'enableGdprCompliance' => false,
'classMap' => [
'User' => 'app\models\user\Model\User',
],
'viewPath' => '#app/views/user',
'controllerMap' => [
//disable for backend
'profile' => [
'class' => Da\User\Controller\ProfileController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'recovery' => [
'class' => Da\User\Controller\RecoveryController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Registration' => [
'class' => Da\User\Controller\RegistrationController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Settings' => [
'class' => Da\User\Controller\SettingsController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
],
],
my User model in backend\models\user\Model looks like this
use Da\User\Model\User as BaseUser;
class User extends BaseUser
{
public static function tableName()
{
return '{{%admin}}';
}
...
...
..
}
the list of RBAC and admin action don't work. i get a 403.
any idea what I'm missing here or did wrong? Thanks.
In the link which was provided for the first step with migration code, next is written
After installing the extension and having configured everything, you
need setup your application with the all the user related stuff, e.g.
You need to run this migration only after you did all installation steps mentioned here. But still it won't work because default user table will be populated, which was created from initial migration. This package creates its own user table and moreover in installation steps there is a Note
Note: If you are using Yii2's Advanced Application Template, before
starting to work with database, please ensure you have deleted
m130524_201442_init.php migration file which comes from the default
installation. It's located at
%PROJECT_DIR%/console/migrations/m130524_201442_init.php path.
Step 1
In your case i would do yii migrate/down 2, which will revert last 2 migrations(init migration contain user table description). Only in case if you didn't add more migrations :)
Total 2 migrations to be reverted:
m190124_110200_add_verification_token_column_to_user_table
m130524_201442_init
In case migration fail, you can run few SQL queries
drop table user;
delete from migration where version='m130524_201442_init';
and then delete m130524_201442_init.php and m190124_110200_add_verification_token_column_to_user_table.php(second one is optional but its your call) files
Step 2
After that according to docs, you need to run rbac + Yii 2 Usuario migrations all together as stated in this note
Note: You will still have to apply Yii 2 RBAC migrations by executing
./yii migrate --migrationPath=#yii/rbac/migrations. Remember that you
have to configure the AuthManager component first. Also, namespaced
migrations were introduced in Yii 2.0.10, so before using them
consider updating your framework installation version. If you are
using a Yii 2 version prior to 2.0.10, you'll have to copy the
migrations located on vendor/2amigos/yii2-usuario/src/User/Migration,
remove its namespaces and add it to your #app/migrations folder.
But before that, you need to move code below from backend/config/main.php to %PROJECT_DIR%/console/config/main.php
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
]
and add authManager into console config for rbac also
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
in final your console/config/main.php should be similar to this
return [
// ....
'controllerMap' => [
// ...
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ...
],
// ...
];
Step 3
Run the migration from note
./yii migrate --migrationPath=#yii/rbac/migrations
Total 13 new migrations to be applied:
Da\User\Migration\m000000_000001_create_user_table
Da\User\Migration\m000000_000002_create_profile_table
Da\User\Migration\m000000_000003_create_social_account_table
Da\User\Migration\m000000_000004_create_token_table
Da\User\Migration\m000000_000005_add_last_login_at
Da\User\Migration\m000000_000006_add_two_factor_fields
Da\User\Migration\m000000_000007_enable_password_expiration
Da\User\Migration\m000000_000008_add_last_login_ip
Da\User\Migration\m000000_000009_add_gdpr_consent_fields
m140506_102106_rbac_init
m170907_052038_rbac_add_index_on_auth_assignment_user_id
m180523_151638_rbac_updates_indexes_without_prefix
m200409_110543_rbac_update_mssql_trigger
Step 4
Create and run migration from first steps without changing model in example.
Step 5
Remove user config from both backend/config/main.php and frontend/config/main.php
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
Apply authManager and user module with proper administrators option to respective config files. This array should contain same role name as in migration which you did in step 4.
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
In the final your frontend and backend config files should be similar to this
return [
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ....
]
// ...
];
Step 6
My favorite step :)
http://yourapp/index.php?r=user/admin visit and enter your creds from migration. Enjoy!

Getting a list of all text that needs to be translated using Yii2 DbMessageSource

I am using Yii2 to work on a project that needs to be translated into various languages. I am using the advanced template and set up my common/main.php like so
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'language' => 'en',
'sourceLanguage' => 'en',
'components' => [
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\DbMessageSource',
'sourceLanguage' => 'en',
],
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'as beforeRequest' => [
'class' => 'common\components\CheckLanguage',
],
];
I have added the required database tables source_message and message. Now each text in the website that I need to have translated I use the Yii::t($category,$message) function.
My question is; How can I get a list of all text in my website that needs to be translated into the database? Do I have to manually scan my site for all Yii::t($category,$message) function calls?
Thanks in advance for your time and input
There is console command provided for this scan functionality.
./yii message
See the documentation in the Guide.
Generate configuration file for the scanner:
./yii message/config-template your/path/to/saving/config.php
Adjust the newly created config.php to your needs.
Run the command:
./yii message path/to/config.php

how to get yii2/admin menu

i am new in yii2 and using advance template .
i am using yii2/admin for roles , permission. but i can't get the menu manage using yii2/admin
the image for the menu manage
like this
how to get this interface for manage menu
i read this
when i run
(index.php?r=admin/menu)
i got an error
Invalid Configuration – yii\base\InvalidConfigException
The table does not exist: {{%menu}}
how to create menu table.
i got a migration file from
vendor/mdmsoft/yii2-admin/migrations/m140602_111327_create_menu_table.php
how to run this migration
please go through with this link MDM Yii2-admin Basic Configuration
add in backend/congif/main.php
'modules' => [
'admin' => [
'class' => 'mdm\admin\Module',
'layout' => 'left-menu', // it can be '#path/to/your/layout'.
'controllerMap' => [
'assignment' => [
'class' => 'mdm\admin\controllers\AssignmentController',
'userClassName' => 'common\models\User',
'idField' => 'id'
],
],
'menus' => [
'assignment' => [
'label' => 'Grand Access' // change label
],
'route' => null, // disable menu route
]
],
],
for run migration use this, through cmd/terminal
yii migrate --migrationPath=#mdm/admin/migrations

Yii2 route using yii\rest\UrlRule with several parameters

I am trying to use Yii 2 routing for REST API.
Following tutorial at http://www.yiiframework.com/doc-2.0/guide-rest-routing.html, I have already defined (with success) a lot of rule for API entry point like so :
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user'
],
],
]
Such a rule defines :
GET /users (list users)
GET /users/123 (show detail of user 123)
Now, my users have games. So I'd like to have urls :
GET /users/123/games (list games of user 123)
GET /users/123/games/864 (details of game 864 for user 123 - such as his scores)
I tried defining my new entry point (withhout success) like so:
'rules' => [
... previous rules ...,
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'game'
],
'tokens' => [
'{userid}' => '<userid:\\d>',
'{gameid}' => '<gameid:\\d>',
],
'patterns' => [
'GET,HEAD /users/{userid}/games' => 'index',
'GET,HEAD /users/{userid}/games/{gameid}' => 'view',
]
]
]
This definition seems wrong because I get a 404 Page not found error.
How should I define my new url routes ?
I would like to use an equivalent format for my definitions, extending 'yii\rest\UrlRule'
I am not sure if this is even possible, the tutorial not mentionning this case.
So I figured out how to use more complex rules.
First, the solution, then the explanation.
Here is the solution:
'rules' => [
... previous rules ...,
[
'class' => 'yii\rest\UrlRule',
'controller' => 'game',
'prefix' => '/users/<userid:\\d+>',
'tokens' => [
'{gameid}' => '<gameid:\\d+>',
],
'patterns' => [
'GET,HEAD' => 'index',
'GET,HEAD {gameid}' => 'view',
]
]
]
And now the explanation:
First my userid / gameid attributes were badly defined. There was a missing "+" after "\d"
The controller seems to be automatically added as a prefix to the patterns. So you have to define both a controller and a prefix (that will be added before the controller).
Parameters in the prefix does not seem to be parsed to find tokens. So I wrote directly the regexp in the prefix instead of adding "userid" as a token.
Finally, there are various "/" automatically added during concatenation of "prefix/controller/pattern" so you don't have to write one.
Do not forget the pluralization rule too ! "game" is singular" but valid urls will be
/users/123/games
/users/123/games/789
Hope it will help.
I think there´s a simple solutions, please try this:
'rules' => [
...
'/users/<userId:\\d+>/games' => 'game/index' ,
'/users/<userId:\\d+>/games/<gameId:\\d+>' => 'game/view' ,
....
];
Just use yii2-nested-rest
It provides REST API for MANY-to-MANY relations in Yii2 framework.
Hope comments will make the magic more understandable:
'rules' => [
// this usual rule for base Yii2 rest usage
['class' => 'yii\rest\UrlRule', 'controller' => ['sitecomponent' ,'sitepage' , 'sitedomain'], 'pluralize'=>false
],
// then rules for yii2-nested-rest
[
// url sitepage/NNN/sitecomponent[/MMM]
// ^^^^^^^^^ ^^^^^^^^^^^^
// resourceName model-endpoint
'class' => 'tunecino\nestedrest\UrlRule',
'modelClass' => 'app\models\SitePage',
'resourceName' => 'sitepage',
'relations' => ['components' => ['sitecomponent'=>'sitecomponent'] ],
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^
// relation name url-endpoint controller]
// defined in model SitePage model-endpoint with Actions from nested
],
[
// cross url sitecomponent/NNN/sitepage[/MMM]
'class' => 'tunecino\nestedrest\UrlRule',
'modelClass' => 'app\models\SiteComponent',
'resourceName' => 'sitecomponent',
'relations' => ['pages' => ['sitepage' => 'sitepage'] ],
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^
// relation name url-endpoint controller
// from model SiteComponent model-endpoint with Actions from nested
],
],
GET xx.com/v2/publication/12/p/34
[
'class' => 'yii\rest\UrlRule',
'pluralize' => false,//controller是否复数
'controller' => 'v2/publication',//此处一定要加上v2
'tokens' => [
'{id}' => '<id:\\d[\\d,]*>',
'{phase}' => '<phase:\\d[\\d,]*>',
],
// 通过extraPatterns和tokens来实现多个参数传递
'extraPatterns' => [
'GET,HEAD {id}/p/{phase}' => 'phase',
],
],
IN ACTION
public function actionPhase($id, $phase){}

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

Categories