I installed yii2 and then added gii to yii2 from this link.
return [
'bootstrap' => ['gii'],
'modules' => [
'gii' => 'yii\gii\Module',
// ...
],
// ...
];
I want to plce this code in application configuration file where it is located?
Application configuration file reside in: project_name/config/web.php
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class'=>'yii\gii\Module',
'allowedIPs'=>['127.0.0.1','192.168.1.*'],
];
You will find a file web.php which is in in the config folder located at your root app folder, the file will contain something like the following:
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'name' => 'My Cool App',//If this line exists change it to your new app name otherwise add it.
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '_4wmrZYaMY7joBAFHrXKpEIFvs9m9S_I',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'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' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'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;
Notice I've added a line: 'name' => 'My Cool App',
Hope this helps.
Related
I need to update SwiftMailer configuration based on user input, particularly, the user may decide to send emails using SMTP protocol or store them locally (in an specific filesystem's folder). The user will use a view to decide the option, then the controller catch the decision and update a session var. The current approach is to read that session var from config/web.php and then choose the appropriate configuration.
I am not sure whether web.php is loaded just once during the application execution, in fact I can not check if the session is active and then get the info from the var. I'm not sure what approach may be the appropriate one.
This is my config/web.php:
<?php
use yii\web\Session;
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$session = Yii::$app->session;
if($session->isActive){
$mailTransport = Yii::app()->session->get('emailtransport');
}
else{ //session is not started
$mailTransport = 'local';
}
if($mailTransport=='local'){
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
'textLayout' => 'layouts/main-text', //template to Send Emails text based
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['clients#ok.com' => 'OK Premiun Clients'],
], //end of messageConfig
// 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,
//'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'ok#gmail.com',
'password' => "password",
'port' => '465',
'encryption' => 'ssl',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
}//end of if loop
else{
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
'textLayout' => 'layouts/main-text', //template to Send Emails text based
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['ok#namesilo.com' => 'OK Premiun Clients'],
], //end of messageConfig
// 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' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'ok#gmail.com',
'password' => "password",
'port' => '465',
'encryption' => 'ssl',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
}//end of if else loop
Because the session is never reached on web.php the emails are always stored locally.
What you are trying to do requires you to instantiate the yii\swiftmailer\Mailer class from within your code and set the transport by calling setTransport(), rather than using it via defining under the components in the config file.
I will give you an example where i will use the smtp.gmail.com as the host for the transport and send an email
public function actionTest(){
//instantiate the mailer
$mailer = new \yii\swiftmailer\Mailer(
[
'useFileTransport' => false
]
);
//set the transport params
$mailer->setTransport(
[
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls'
]
);
//to email
$to = "someemail#gmail.com";
//email subject
$subject = "this is a test mail";
//email body
$body ="Some body text for email";
//send the email
$mailer->compose()->setTo($to)->setFrom(
[
'support#site.com' => 'Site Support'
]
)->setTextBody($body)->setSubject($subject)->send();
}
Another solution is this: I did some changes using my Model Class:
public function sendMail($transport, $view, $subject, $params = []){
//set layout params
\Yii::$app->mailer->getView()->params['userName'] = $this->username;
if($transport == 'local'){
\Yii::$app->mailer->useFileTransport=true;
}
else{
\Yii::$app->mailer->useFileTransport=false;
}
$result = \Yii::$app->mailer->compose([
'html' => 'views/' . $view . '-html',
'text' => 'views/' . $view . '-text',
], $params)->setTo([$this->email => $this->username])
->setSubject($subject)
->send();
//reset layout params
\Yii::$app->mailer->getView()->params['userName'] = null;
return $result;
} //end of sendMail
It helped me to simplify my web.php, it wasn't necessary to use session vars.
If I add this configuration of the cms module to the config file
'cms' => [
'class' => 'yii2mod\cms\Module',
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => '',
'froalaEditorOptions' => [
'clientOptions' => [
'heightMin' => 300,
'theme' => 'dark',
'imageUploadURL' => 'upload-image',
'imageManagerDeleteURL' => 'delete-image',
'imageManagerDeleteMethod' => 'POST',
'imageManagerLoadURL' => 'images'
],
'excludedPlugins' => [
'file',
'emoticons'
]
],
'enableMarkdown' => false
]
It adds the default route of this module to all the routes like this
/cms/site/login /cms/site/index /cms/site/error. Why this is happening and how i can remove this?
If you want to remove the /cms module prefix by default, you can add a global route to backend/config/main.php(If you use advanced templates): '<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'.
for example:
// backend/config/main.php
return [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'
],
],
];
Access in your bowser: www.xxx.com/site/index, it is forwarded to: /cms/site/index
I install yii2-rbac following this site page: https://github.com/dektrium/yii2-rbac/blob/master/docs/installation.md .
I do it second time. First time I have done, but I wrote in the config/web.php file:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
I did not know, that 'rbac' => 'dektrium\rbac\RbacConsoleModule' it must write in the console.php (not in web.php).
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
],
`
This code I have wrote in both config files: web.php and console.php, but in the web.php I have wrote 'rbac' => 'dektrium\rbac\RbacConsoleModule' and in console.php I have not wrote it, but all worked: yii2-rbac has been installed succeful. And all transaction have passed succeful. But 'rbac' => 'dektrium\rbac\RbacConsoleModule' in web.php seems to me wrong. It isn't web module, it is console module. Then I have rollbacked transactions (migrate/down) and I have removed rbac at all by removing from composer.json "dektrium/yii2-rbac": "1.0.0-alpha#dev" declaration. All has been removed.
Than I began to install rbac second time. After composer installation I have wrote in the web.php:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
'rbac' => 'dektrium\rbac\RbacWebModule',
//'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
and in console.php I have wrote:
'modules' => [
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
The site on yii2 don't work after it!!! I have changed in the web.php "...RbacConsoleModule". Site works. Why it don't work with RbacWebModule? Then I tried to apply transactions, that I have rollbacked before, but raise error: You have wrong authManager configuration
enter image description here
What can I do? Help me. Ecscuse me for my English. I'm from Russia.
my console.php:
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
]
],
'modules' => [
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
//....
my web.php:
//This all in $component
'db' => require(__DIR__ . '/db.php'),
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
],
That all! The problem has been decided. It must write authManager section to modules, not in components:
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
//'defaultRoles' => ['guest'],
]
//'rbac' => 'dektrium\rbac\RbacWebModule',
'rbac' => 'dektrium\rbac\RbacConsoleModule',
]
you need write that:
'components' => [
'authManager' => [
'class' => 'dektrium\rbac\components\DbManager',
'defaultRoles' => ['users'],
],
...
i want to put a log in app.log ,My config file
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
'file' => [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'logFile' => '#root/console/runtime/logs/app.log',
],
]
]
in controller action
public function actionRankCalculation()
{
$allConest = Contest::find()->where('isActive = 1')->all();
Yii::trace('start calculating average revenue');
$response = [];
/** #var Contest $contest */
foreach ($allConest as $contest) {
$videoQuery = Video::find()->where('contest_id = ' . $contest->id);
$videoQuery->andWhere('isActive = 1');
$videoQuery->orderBy([
'global_likes' => SORT_DESC,
'id' => SORT_ASC,
]);
}
But Yii::trace('start calculating average revenue'); not working
You try this.Use categories. For example like below
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error'],
'categories' => ['test1'],
'logFile' => '#app/Test/test1.log',
],
And use below one in controller action
public function actionIndex(){
Yii::error('Test index action', $category = 'test1'); }
Try to set both flushInterval and exportInterval to 1 in console config:
return [
'bootstrap' => ['log'],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 1,
],
],
'flushInterval' => 1,
],
],
];
It makes each log message appearing immediately in logs.
We've been working on a project with Yii2 Advanced App, with a custom bootstrap template. I've generated the crud using gii. All other CRUDs work fine. But the User crud displays Yii2 User Module not the CRUD.
I've gone through amnah's complete documentations and couldn't find any solutions in any other places either. I even tried Yii2 documentations and it wasn't any help either.
This is my backend config
<?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')
);
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => 'sahasa/index',
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'request' => [
'baseUrl' => $baseUrl,
],
'user' => [
'class' => 'amnah\yii2\user\components\User',
],
// 'user' => [
// 'identityClass' => 'common\models\User',
// 'enableAutoLogin' => true,
// ],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
'modules' => [
'user' => [
'class' => 'amnah\yii2\user\Module',
// set custom module properties here ...
],
'debug' => [
'class' => 'yii\debug\Module',
],
],
];
This is what I get when I goto localhost/app/backend/web/index.php?r=user
I want it to display a CRUD similar to this
I'm stuck there. Without the CRUD it'll be difficult to manage the USERS.
Any help is appreciated.
Thanks in advance.
I think you need to redefine the controller too. You need a new controller derived form the original controller for correctly addressing the new CRUD element.
I suppose your controller is in backend and is named user otherwise change properly the following example (part of config/main.php):
'user' => [
...
'controllerMap' => [
'user' => 'backend\controllers\user',
],
],
You can add this code to Controller in backend
public function init()
{
$user_id = Yii::$app->getUser()->id;
if($user_id){
$user = \amnah\yii2\user\models\User::findOne($user_id);
if ($user->can("admin")) {
// do something
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
}else{
throw new HttpException(403, 'You are not allowed to perform this action.');
}
parent::init();
}
Just click the link /user/admin
You'll get CRUD for users.