I have setup Yii2 nested module and I want to set different configuration and each modules has own component and other settings with there own models
Like in School Management System, I have created a nested module like V1 is my API (main module) and under these, I have created a Student module, Teacher module, Parent module, driver module, admin module each has a different table and different model. I want to login differently with each user like..
API calls for each
https://example.com/v1/admin/login
https://example.com/v1/student/login
https://example.com/v1/parent/login
https://example.com/v1/user/login
https://example.com/v1/driver/login
How can I manage these login and their own configuration?
Thanks
Jitendra
In the module Class you can set components, aliases and other settings and using something like this:
Here is an example for the admin module:
class Admin extends Module
{
// ...
/**
* {#inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
$this->setComponents([
// array of components
]);
// ...
}
}
or if you prefer you can set the components like this
$this->components = [
// array of components
]);
if you are using nested modules, you are already specifying "settings" for the module - i.e all sub modules
To use different login for all modules when specifying components set different name for the identityCookie of the user component for each module.
Example for admin module:
$this->components => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-admin', 'httpOnly' => true],
],
// ... other components
Related
I need to check the records in the notifications table at every page load of every controller.
So I wrote it in a component and the component is executed in the bootstraping process.
I need the notifications to be available in the layout so that i can show them in the notification menu.
below is what I have tried so far:
component:
namespace admin\components;
use Yii;
use yii\base\Component;
use admin\models\Notification;
class NotificationManager extends \yii\base\Component{
public function init() {
$notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
//echo "<pre>"; print_r($notifications);exit;
if(count($notifications)>0){
foreach ($notifications as $notif) {
if($notif['type'] == 'courier')
$courier_notifications[] = $notif;
elseif($notif['type'] == 'order')
$order_notifications[] = $notif;
}
Yii::$app->view->params['courier_notifications'] = $courier_notifications;
Yii::$app->view->params['order_notifications'] = $order_notifications;
}
}
}
Layout:
$courier_notifications = $this->params['courier_notifications'];
I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.
Im not sure why your component execution during bootstrap fails to add the value to params.But believe it to be an overkill.
You can rather move the logic to component method and access in layout whenever necessary
Component.
namespace admin\components;
use Yii;
use yii\base\Component;
use admin\models\Notification;
class NotificationManager extends Component{
public function notifications($type = 'courier') {
$notifications = Notification::find()
->where(['type' => $type])
->orderBy('id DESC')
->asArray()->all();
return $notifications;
}
}
Add the component class under Components section in your config file
'notificationManager ' => [
'class' => 'admin\components\NotificationManager'
]
Layout
$courier_notifications = yii::$app->notificationManager->notifications('courier');
If you really want to go bootstrap mode, you need to implement yii\base\BootstrapInterface and put your logic in the bootstrap($app) method in order for the param to be available site-wide by setting the value of Yii::$app->params['notifications'] to the result of your logic.
Another common approach is to add a new method public function displayNotifications or whatever you want to name it, to your component, move all the logic in it and then in your layout/view etc., call it with Yii::$app->notificationManager->displayNotifications(). You can also pass additional parameters to it and enhance your logic.
notificationManager has to be replaced with the name you registered your custom component in the Yii app config (web.php for basic app, main.php for advanced app).
LE - If you only registered your component for bootstrap, you should also register it in the components array.
'notificationManager' => [
'class' => '\admin\components\NotificationManager'
]
I just implementing a new gii generator for my requirement on yii2.
i want to know best place to keep those codes?
Create app\modules\gii directory with own Generator class, views, templates.
namespace app\modules\gii;
class MyCustomGenerator extends \yii\gii\generators\crud\Generator
{
// ...
public function generate()
{
// ...
}
}
Then enable it in gii configuration.
[
// ...
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'generators' => [
'class' => '\app\modules\gii\MyCustomGenerator',
'model' => ['class' => '\app\modules\gii\model\MyCustomGenerator'],
],
],
],
]
Which module of gii that you need to custom?
If it is CRUD module, I think you should put it into app/backend/ because it just use for this app.
Here is my customization: custom crud gii templates
My folder structure: yii2 - custom gii crud templates - folder structure
No good idea own gii template put in app/modules/gii. Better is create separate module. Benefits:
can reuse in other projects
if put it in composer under require_dev, do not install on production
Using the "basic" application template, what is the correct way of setting up a module login that is separate from the main site login?
For example I have an "admin" module which requires a login. I also need a user login for the main site.
I have done the following:
Created admin module using gii tool
Created models folder within the admin module folder
Placed LoginForm.php and User.php within this folder (also updated the namespace declarations in these files)
Added AccessControl behaviour and login/logout actions to modules\admin\controllers\DefaultController.php
Updated config\web.php as follows:
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],
Updated app\modules\admin\Module.php as follows:
public function init()
{
parent::init();
Yii::$app->set('user', [
'class' => 'yii\web\User',
'identityClass' => 'app\modules\admin\models\User',
'enableAutoLogin' => true,
'loginUrl' => ['admin/default/login'],
]);
Yii::$app->set('session', [
'class' => 'yii\web\Session',
'name' => '_adminSessionId',
]);
}
The problem I am having is that if I try to access an admin page when I am not logged in, it shows the login form (this is correct). However upon logging in, it is just redirects me back to the main site. It should redirect me to the admin page I was trying to access.
In DefaultController.php, it has the following (default code):
if ($model->load(Yii::$app->request->post()) && $model->login())
return $this->goBack();
What is the correct way of doing this so I can have independent logins for the admin module and for the main site? I don't want to use the "advanced application template" as that adds some unnecessary complexity.
The User component allows you to set a returnUrl, the getter explained: This method reads the return URL from the session. It is usually used by the login action which may call this method to redirect the browser to where it goes after successful authentication.
Recommended: Before processing the data, set the returnUrl by calling Yii::$app->user->setReturnUrl(Url::current()); (this will store the page the user was on in the session, moreover, you can manipulate GET parameters using Url::current() before passing it to the session), and let the framework do its magic.
Not recommended: After processing the data, you can rely on referrer (which won't work in some cases) as following
return Yii::$app->request->referrer ? $this->redirect(Yii::$app->request->referrer) : $this->goHome(); or instead of goHome which basically redirects to app->homeUrl that can be set during Module init, you could say $this->redirect('your/admin/index');
I recommend setting the ['homeUrl' => 'your/admin/index'] during the initialization of the Module, as you might need it for other features as well and Yii2 uses it as a "fallback" to some redirects as well.
The best way is to create new controller in the admin module, which should have login, logout actions. Because, in future you may add there some extra logic.
In that login action you can use same LoginForm.
You can specify redirect url in that login action.
Admin module class can looks like this:
namespace app\modules\admin;
class Module extends \yii\base\Module
{
public $layout = 'main';
public $defaultRoute = 'main/index';
public function init()
{
parent::init();
Yii::$app->errorHandler->errorAction = '/admin/main/error';
Yii::$app->user->loginUrl = '/admin/main/login';
.....
}
}
goBack() defaults to the homeUrl if the returnUrl for the user hasn't been set.
Why not just redirect?
if ($model->load(Yii::$app->request->post()) && $model->login())
return $this->redirect(['myadminmodule']);
go to config/web.php and add it to the components
'backendUrlManager'=>[
'class' => 'yii\web\urlManager',
'enablePrettyUrl'=>true,
'showScriptName'=>false,
'baseUrl'=>'/admin',
],
In DefaultController.php, it has the following (default code):
if ($model->load(Yii::$app->request->post()) && $model->login())
return Yii::$app->getResponse()->redirect(Yii::$app->backendUrlManager->baseUrl);
I am using Yii2 Advanced Template. I have created user module inside /frontend/modules/ directory. without theme integration, views are called from /modules/user/views/ directory.
Currently, I have created three different themes inside /frontend directory. So I would like to access views from theme directory for User Module. How it would be possible?
It is possible to set layout for module by
$this->layoutPath = \Yii::getAlias('/themes/classic/views/layouts/');
$this->layout = 'userLayout';
But How views can be accessed from theme directory for module?
Please suggest possible solutions..
I found solution to my question. I have implemented following way.
Added Layout path in Module.php after init() method.
public function init()
{
parent::init();
$this->layoutPath = \Yii::getAlias('#app/themes/classic/views/layouts/');
$this->layout = 'userLayout';
}
and
added theme configuration with module views in main.php config file
'view' => [
'theme' => [
'pathMap' => [
'#app/views' =>'#app/themes/classic/views/',
'#app/modules'=>'#app/themes/classic/modules',
'#app/widgets'=>'#app/themes/classic/widgets'
],
'baseUrl'=>"/themes/classic",
],
],
I would like to check if my user have filled certain fields in his profile before he can access any action of any controller.
For example
if(empty(field1) && empty(field2))
{
header("Location:/site/error")
}
In yii1 I could do it in protected\components\Controller.php in init() function
But in yii2 I'm not sure where to put my code. I cannot modify core files, but not sure what to do in backend of my advanced application to make it work.
I know I can user beforeAction() but I have too many controllers to do that and to keep track of every controller
In case you need to execute a code before every controller and action, you can do like below:
1 - Add a component into your components directory, for example(MyGlobalClass):
namespace app\components;
class MyGlobalClass extends \yii\base\Component{
public function init() {
echo "Hi";
parent::init();
}
}
2 - Add MyGlobalClass component into your components array in config file:
'components' => [
'MyGlobalClass'=>[
'class'=>'app\components\MyGlobalClass'
],
//other components
3 - Add MyGlobalClass into bootstarp array in config file:
'bootstrap' => ['log','MyGlobalClass'],
Now, you can see Hi before every action.
Please note that, if you do not need to use Events and Behaviors you can use \yii\base\Object instead of \yii\base\Component
Just add in config file into $config array:
'on beforeAction' => function ($event) {
echo "Hello";
},
Create a new controller
namespace backend\components;
class Controller extends \yii\web\Controller {
public function beforeAction($event)
{
..............
return parent::beforeAction($event);
}
}
All your controllers should now extend backend\components\Controller and not \yii\web\Controller. with this, you should modify every controller. I would go for this solution.
I believe you might also replace 1 class with another (so no change to any controller necessary), something like
\Yii::$classMap = array_merge(\Yii::$classMap,[
'\yii\web\Controller'=>'backend\components\Controller',
]);
See more details here: http://www.yiiframework.com/doc-2.0/guide-tutorial-yii-integration.html and I took the code from here: https://github.com/mithun12000/adminUI/blob/master/src/AdminUiBootstrap.php
you can put this in your index.php file. However, make sure you document this change very well as somebody that will come and try to debug your code will be totally confused by this.
Just i think this code on config file can help you:
'on beforeAction' => function ($event) {
// To log all request information
},
'components' => [
'response' => [
'on beforeSend' => function($event) {
// To log all response information
},
],
];
Or, https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md use RBAC, to restrict access to controllers actions one at a time based on rules. Why would you want to restrict access to controller actions based on user fields is beyond me. You will not be able to access anything (including the login form) if you put a restriction there.