Yii2 Is it possible to use translation in common dir? - php

I'm trying to translate a constants file located in common/php/ that I use for error messages.
The constants are defined like this:
define("CONSTANT_NAME", Yii::t('common/error', 'Error message'));
I have the following in common/config/main.php:
'i18n' => [
'translations' => [
'backend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages',
'sourceLanguage' => 'it-IT',
'fileMap' => [
'backend' => 'app.php',
],
],
'common*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'sourceLanguage' => 'it-IT',
'fileMap' => [
'common' => 'app.php',
'common/error' => 'error.php',
],
],
'frontend*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#frontend/messages',
'sourceLanguage' => 'it-IT',
'fileMap' => [
'frontend' => 'app.php',
],
],
],
],
It's working for backend and frontend but it's not working for the constant file located in common. Am I trying to do something that is not possible?

if you are trying to translate from it-IT to en-US then add this to your common/config/main.php:
'sourceLanguage'=>'it-IT',
'language'=>'en-US',

Related

Getting unknown property: Da\User\Module::isGuest yii2-usuario

I'm install 2amigos/yii2-usuario:~1.5.1 on a yii2-basic-template, using https://yii2-usuario.readthedocs.io/en/latest/. However, it returns this error (Getting unknown property: Da\User\Module::isGuest yii2-usuario) in any view.
My config/console.php:
'components' => [
...
'authManager' => [
'class'=> 'yii\rbac\DbManager',
],
...
],
'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',
],
],
],
My config/web.php:
'components' => [
...
'user' => [
'class' => Da\User\Module::class,
'classMap' => [
'User' => app\models\User::class,
],
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'view' => [
'theme' => [
'pathMap' => [
'#Da/User/resources/views' => '#app/views/user'
]
]
]
],
I managed to solve it with help.
Follow the line:
Remove : config/web.php
'user' => [
'identityClass' => 'app\models\Users',
'enableAutoLogin' => true,
'enableSession' => true,
],
'user-management' => [
'class' => 'webvimark\modules\UserManagement\UserManagementModule',
'on beforeAction'=>function(yii\base\ActionEvent $event) {
if ( $event->action->uniqueId == 'user-management/auth/login' ){
$event->action->controller->layout = 'loginLayout.php';
};
},
],
add into config/web.php:
'components' =>[ ...
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'view' => ['theme' => [ 'pathMap' => ['#Da/User/resources/views' => '#app/views/user']]] //If your view is modified.
]
'modules' => ['user' => [
'class' => \Da\User\Module::class,
'allowAccountDelete' => true,
'enableRegistration' => false,
'administratorPermissionName' => 'user-management']
...]
``

How to override view via themes? (yii2)

I need to override a view file like ‘pathMap’ => [ ‘#dektrium/user/views’ => ‘#app/views/site’] I followed manual (https://github.com/dektrium/yii2-user/blob/master/docs/overriding-views.md) but all I see is the old view whatever I do. Perhaps something wrong with baseUrl or basePath but I’m not sure what I should do.
frontend/config/main.php:
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
'baseUrl' => '/',
],
// .................
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
'<action:\w+>' => 'site/<action>',
],
],
'view' => [
'class' => 'yii\web\View',
'theme' => [
//'basePath' => '#app/themes/basic',
//'baseUrl' => '#app/views/site',
'pathMap' => [
'#dektrium/user/views' => '#app/views/site'
]
]
]
//.................
]
common/config/main.php:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'admins' => ['admin'],
'modelMap' => [
'User' => 'common\models\User',
],
]
I open page on the address like mydomain.test/user/register (in case it’s somehow matter)
I also tried to put ‘view’ part in components of common/config/main.php and of module. Tried to create themes folder and put new view therein, nothing seems work
ok, I finally fixed it
'view' => [
'class' => 'yii\web\View',
'theme' => [
'basePath' => '#frontend/views/site',
'baseUrl' => '#frontend/views/site',
'pathMap' => [
'#dektrium/user/views/registration' => '#frontend/views/site',
]
]
]

urlManager for module Yii2

I've got a basic Yii2 project, in which i created a separate module "rest". I have set up urlManager in config/web.php file. It works fine for common url, but it seems to me it is not working with url starting with my module name: rest/.. I have actionAuth() in AuthController in my rest module, and it is accessible with this url: test.ru/auth/auth. But i want it to be accessible with this url:test.ru/auth. I tried to write like this in web.php :
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\auth',
'extraPatterns' => [
'POST /' => 'auth',
],
'pluralize' => false,
],
],
],
But it does not work(not found error in browser).
I also tried like this:
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\auth',
'extraPatterns' => [
'POST rest/auth' => 'auth',
],
'pluralize' => false,
],
],
],
It seems to me that urlManager does not want to work for module. Next i tried to write the same code in my Module.php in rest/ directory. But it produced many errors. I think because of the same error things like that dont work too:`
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\city',
'extraPatterns' => [
'DELETE {id}' => 'delete',
],
`
So my question is: how to set up urlManager for module in Yii2? I need to configure HTTP DELETE method, post methods work without any settings in urlManager.
The whole web.php file:
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'language' => 'ru',
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'xxxxxxx',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
// 'loginUrl' => ['site/login'],
],
'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' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\user',
'except' => ['delete', 'create', 'update', 'index'],
'extraPatterns' => [
'GET all' => 'all',
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\auth',
'extraPatterns' => [
'POST reg' => 'reg',
'POST auth' => 'auth',
'POST rest/auth' => 'auth',
],
'pluralize' => false,
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest\city',
'extraPatterns' => [
'DELETE {id}' => 'delete',
],
],
],
],
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
// 'basePath' => '#app/messages', // if advanced application, set #frontend/messages
'sourceLanguage' => 'en',
'fileMap' => [
//'main' => 'main.php',
],
],
],
],
],
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
'manager' => [
'class' => 'app\modules\manager\Module',
],
'rest' => [
'class' => 'app\modules\rest\Module',
],
'rbac' => [
'class' => 'mdm\admin\Module',
'controllerMap' => [
'assignment' => [
'class' => 'mdm\admin\controllers\AssignmentController',
/* 'userClassName' => 'app\models\User', */
'idField' => 'id',
'usernameField' => 'username',
],
],
'layout' => 'left-menu',
'mainLayout' => '#app/views/layouts/admin.php',
]
],
'aliases' => [
//'#mdm/admin' => 'app/mdm/admin',
],
'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;
My Module.php code(commented code shows my attempt to write urlManager):
<?php
namespace app\modules\rest;
/**
* rest module definition class
*/
class Module extends \yii\base\Module
{
/**
* #inheritdoc
*/
public $controllerNamespace = 'app\modules\rest\controllers';
/**
* #inheritdoc
*/
public function init()
{
parent::init();
// custom initialization code goes here
\Yii::$app->user->enableSession = false;
$config = [
'components' => [
'basePath' => dirname(__DIR__),
// 'user' => [
// 'identityClass' => 'app\models\User',
// 'class' => 'app\models\User',
// 'enableSession' => false
// ],
// 'urlManager' => [
// 'enablePrettyUrl' => true,
// 'enableStrictParsing' => true,
// 'showScriptName' => false,
// 'rules' => [
// [
// 'class' => 'yii\rest\UrlRule',
// 'controller' => 'rest\city',
// 'extraPatterns' => [
// 'DELETE {id}' => 'delete',
// ],
// ],
// ],
// ],
'response' => [
'format' => \yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if(( $response->statusCode >= 200) && ( $response->statusCode < 300)) {
if(isset($response->data['_appErr'])) {
unset($response->data['_appErr']);
$response->data = [
'success' => false,
'error' => $response->data,
'data' => null,
];
} else {
$response->data = [
'success' => $response->isSuccessful,
'error' => null,
'data' => $response->data,
];
}
} else {
if($response->statusCode == 401) {
$response->data = [
'success' => false,
'error' => [
'code' => 9,
'message' => 'Unauthorized',
'user_msg' => 'You need to be authorized',
],
'data' => null,
];
}
// else {
// $response->data = [
// 'success' => false,
// 'error' => [
// 'code' => 1,
// 'message' => 'server has returned '.$response->statusCode.' error',
// ],
// 'data' => null,
// ];
// }
}
},
],
],
];
\Yii::configure(\Yii::$app, $config);
}
}
Try this:
namespace yii\rest;
class UrlRule extends Object implements UrlRuleInterface {
public function parseRequest($manager, $request) {
list($e1, $e2) = sscanf($request->getPathInfo(), '%[a-zA-Z]/%[a-zA-Z]');
if ($e1 === 'auth' && $e2 === '') {
return ['/auth/auth', $request->queryParams];
}
return false;
}
}
Use forward slash(/) while defining the controller value in the rules array.
This will work:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest/user',
'except' => ['delete', 'create', 'update', 'index'],
'extraPatterns' => [
'GET all' => 'all',
]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest/auth',
'extraPatterns' => [
'POST reg' => 'reg',
'POST auth' => 'auth',
],
'pluralize' => false,
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'rest/city',
'extraPatterns' => [
'DELETE {id}' => 'delete',
],
],
]
Check out the documentation here: http://www.yiiframework.com/doc-2.0/guide-rest-versioning.html

call Yii::$app frontend from backend yii2

i install this plugin for change theme in frontend https://github.com/Singrana/thememanager
install like manual.
in my frontend/config/main.php
'components' => [
'view'=>
[
'theme' =>
[
'class' => 'singrana\thememanager\components\ThemeManager',
'current' => 'siteeee',
'themes' =>
[
'site' =>
[
'pathMap' =>
[
'#app/views' => '#frontend/themes/site',
'#app/views/layouts' => '#frontend/themes/site/layouts',
],
//'defaultLayout' => '//inner',
],
'siteeee' =>
[
'pathMap' =>
[
'#app/views' => '#frontend/themes/siteeee',
'#app/views/layouts' => '#frontend/themes/siteeee/layouts',
],
//'defaultLayout' => '//inner',
],
],
],
],
],
but i need to call \Yii::$app->view->theme->changeTheme('themeName');, like in manual, to change theme , how can i do this in backend side ?

Yii2 - Filsh OAuth2 Server Installation

I am currently trying to install a Yii2 extension for implementing an OAuth2 server (https://github.com/Filsh/yii2-oauth2-server). However, I keep running on the error below:
Does anyone have an idea on how to install this extension. I followed the instructions given but there was no mention about that error.
Satya is right. You need to configure oauth2 module as described on repo's description:
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'options' => [
'token_param_name' => 'accessToken',
'access_lifetime' => 3600 * 24
],
'storageMap' => [
'user_credentials' => 'common\models\User'
],
'grantTypes' => [
'client_credentials' => [
'class' => 'OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials'
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
],
]
I've configured this extension successfully and created Yii2 Rest API template with OAuth2 server https://github.com/ikaras/yii2-oauth2-rest-template - feel free to use. Also this code has some demo data (examples of using) and support of scopes for controllers.
Add give 'oauth2' configuration in 'modules' section of config/main.php.
It may work
Use this configuration under your confin/main.php file under modules section.
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'token',
'tokenAccessLifetime' => '100800', // Expiry Time
'storageMap' => [
'user_credentials' => 'common\models\User', // This Should be your model name
],
'grantTypes' => [
'client_credentials' => [
'class' => 'OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false,
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true,
'refresh_token_lifetime' => '100800',
],
],
];
Found solution my-self on scope issue, maybe it will be useful for someone - marked with ** in config:
'modules' => [
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24,
'storageMap' => [
'client_credentials' => 'app\models\User',
'user_credentials' => 'app\models\User',
**'scope' => 'app\models\User',**
],
'grantTypes' => [
'client_credentials' => [
'class' => '\OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false,
'always_issue_new_refresh_token' => true
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
]
]
],

Categories