How to override the class module in the config of my theme? I tried so impossible.
return [
...
'modules' => [
'shop' => [
'class' => 'app\modules\shop\ShopModule',
'components' => [
'manager' => [
'class' => 'app\web\theme\modules\shop\Customer',
],
],
],
...
],
];
Overriding controllers
Sometimes you may need to override default Yii2-user controllers. It is pretty easy and takes two steps.
Step 1: Create new controller
First of all you need to create new controller under your own namespace (we’d recommend app\controllers\user) and extend it from needed Yii2-user controller.
For example, if you want to override AdminController you should create app\controllers\user\AdminController and extend it from dektrium\user\controllers\AdminController:
<?php
namespace app\controllers\user;
use dektrium\user\controllers\AdminController as BaseAdminController;
class AdminController extends BaseAdminController
{
public function actionCreate()
{
// do your magic
}
}
Step 2: Add your controller to controller map
To let Yii2-user know about your controller you should add it to controller map as follows:
<?php return [
...
'modules' => [
...
'user' => [
'class' => 'dektrium\user\Module',
'controllerMap' => [
'admin' => 'app\controllers\user\AdminController'
],
...
],
...
],
For overriding view click here
Related
i was trying to make
this url
http://localhost/advanced/frontend/web/index.php?r=test
into
htttp://localhost/advanced/frontend/web/tests in yii2
also to receive post request
this in my codding in common/config/main.php
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
],
'urlManagerFrontEnd' => [
'enablePrettyUrl' => true,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['test'],
'only' => ['index', 'create'],
],
],
'showScriptName' => false,
],
],
];
this in my frontend testController
namespace frontend\controllers;
use Yii;
use yii\rest\ActiveController;
use common\models\Test;
use yii\data\ActiveDataProvider;
class TestController extends ActiveController {
public $modelClass = 'common\models\Test';
public function actions(){
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function actionCreate(){
$model = new Test();
$model->load(Yii::$app->request->post(),'');
$model->save();
return $model;
}
}
i have a problem in the post request when i tried
Postman result jpg
so i have 2 problem the first is the prettyUrl and the post request
if u have a solution please make it easy because i just learn php yii2 html css etc for 1 month
You know, yii2 with adminlte is exist in this git .
But if I use this using composer, it not gives me an educate.
You know, I want to learn step by step.
So I tried like this:
I download adminlte in his official.
In this zip file, I have one folder with name : "AdminLTE: 2.*"
Then I Extract all the item in folder AdminLTE:2.* into vendor/bower/adminLTE/"bunch of file"
Now, I edit assets/AppAsset like this:
class AppAsset extends AssetBundle {
public $basePath = '#webroot';
public $baseUrl = '#web';
public $sourcePath = '#bower/'adminLTE';
public $css = [
'adminLTE/dist/css/AdminLTE.min.css',
'css/site.css',
];
public $js = [
'adminLTE/dist/js/app.js'
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}
But, both css and js below is 404 ?
Any help it so appreciated
If you want to manually add AdminLTE there is no need to put it in the bower folder.
Place it in the /web folder (in case of Advanced Template it's /frontend/web or /backend/web).
You have got AppAsset already set for this folder but you have to remove $sourcePath because when this is set $basePath and $baseUrl are overriden.
Do not add theme inside the vendor for manual installation of theme. Follow below mentioned steps.
Step 1 : Download your adminlte and create a directory named theme inside a root
ex. your_project/basic/themes ( i.e outside the web directory)
Step 2 : paste your adminlte theme folder inside newly created theme directory
Step 3 : Now you need to create asset to register all the csss and js required for adminlte theme
go to your_project/basic/assets directory and create a new file lets say, AdminLTEAsset.php
namespace app\assets;
use yii\web\AssetBundle;
/**
* #author Qiang Xue <qiang.xue#gmail.com>
* #since 2.0
*/
class AdminLTEAsset extends AssetBundle {
public $sourcePath = '#app/themes/adminlte/';
public $css = [
'dist/css/AdminLTE.css',
'font-awesome-4.5.0/css/font-awesome.min.css',
'ionicons/2.0.1/css/ionicons.min.css',
'dist/css/skins/_all-skins.min.css',
];
public $js = [
'dist/js/app.js',
'plugins/slimScroll/jquery.slimscroll.min.js',
'plugins/fastclick/fastclick.min.js',
'dist/js/demo.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}
Step 4: Now go to the themes/adminlte/layouts/main.php and register your newly created AdminLTEAsset. as follows.
$assets = app\assets\AdminLTEAsset::register($this);
$basUrl = $assets->baseUrl;
Step 5 : in your /config/web.php file add the following pathmap
'components'=>[
'view' => [
'theme' => [
'pathMap' => ['#app/views' => '#app/themes/adminlte'],
'baseUrl' => '#web/../themes/adminlte',
],
],
]
Embeding admin lte theme i yii2 basic
1) create yii project using composer
sudo du
cd /var/www/html
composer create-project yiisoft/yii2-app-basic basic 2.0.4
2)now create it accessible
chmod 777 -R project name
3) download admin lte theme by using
git clone https://github.com/bmsrox/baseapp-yii2basic-adminlte.git
4) now update composer
composer update
if token error then create account in git and create token in setting tab by clicking genarate new token
copy and provide it to composer
5) update your web.php file in config
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'layout'=>'column2',
'layoutPath'=>'#app/themes/adminLTE/layouts',
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
''=>'site/index',
'<action:(index|login|logout)>'=>'site/<action>',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>'
],
],
'view' => [
'theme' => [
'pathMap' => ['#app/views' => '#app/themes/adminLTE'],
'baseUrl' => '#web/../themes/adminLTE',
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'n0VkMX1RmIa_ovJmwR3Gn_hdZyQ7SyKe',
],
'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' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
//$config['modules']['gii'] = 'yii\gii\Module';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'generators' => [ //here
'crud' => [ // generator name
'class' => 'yii\gii\generators\crud\Generator', // generator class
'templates' => [ //setting for out templates
'custom' => '#vendor/bmsrox/yii-adminlte-crud-template', // template name => path to template
]
]
],
];
}
return $config;
6) update SiteController. Php in controller folder
replace actionLogout with following code
public function actionLogout()
{
Yii::$app->user->logout();
return $this->redirect(Yii::$app->user->loginUrl);
}
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
// change layout for error action
if ($action->id=='login')
$this->layout = 'login';
return true;
} else {
return false;
}
}
7) if misconfiguration error then
update apche2
by using command
a2enmod rewrite
and restrart apache using
service apache2 restart
finished...........
best of luck
I'm foregoing Yii2's bundled jQuery and Bootstrap assets in exchange for ones I've bundled myself using npm/browserify So step one was to remove jQuery and Bootstrap from yii\web\YiiAsset via the config:
'components' => [
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
...
]
I want to put this in the footer, obviously, but it needs to load before any other assets so that jQuery is available to them.
Here's my AssetBundle:
class AppAssets extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $depends = [
'app\assets\CustomAssets',
'yii\web\YiiAsset',
];
}
With my CustomAssets bundle (that contains my own JS and CSS) declared first in depends, I think this would work, but I also have an ActiveForm on the page, and this registers its own asset bundle, which is dependent on the various Yii assets. Here's where I embed that form:
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
...
<?php ActiveForm::end(); ?>
Is there a way I can override the depends on ActiveFormAsset so that it also depends on my scripts?
Since asset bundle dependencies are transitive, it occurred to me that in the same way I'm overriding the config for the Jquery and Bootstrap bundles, I can override the config for yii\web\YiiAsset like so:
'components' => [
'assetManager' => [
'bundles' => [
...
'yii\web\YiiAsset' => [
'depends' => [
'app\assets\CustomAssets',
],
],
],
],
...
]
So when ActiveFormAsset tries to load yii\web\YiiAsset, it processes the dependency on my own scripts/styles, and also covers any other assets that get loaded and might depend on yii\web\YiiAsset.
what i did was replacing shipped assets, instead of killing them:
'bundles' => [
'yii\bootstrap\BootstrapAsset' => ['class' => 'common\assets\BootstrapAsset',],
'yii\bootstrap\BootstrapPluginAsset' => ['class' => 'common\assets\BootstrapPluginAsset',],
],
How I can restrict access to RBAC Module itself?
I'm using yii\rbac\DbManager and I have created a module(Authorization) in backend for permission assignment,create auth items, now I want to make sure only admin can access this module!
In controller I have used something this and it's working fine.
use yii\filters\AccessControl;
class MyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete'], //only be applied to
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update','delete'],
'roles' => ['admin'],
],
],
],
.........
I have put this in Authorization.php init function but nothing happen, all auth controllers are accessable.
public function init()
{
if(\Yii::$app->user->can('admin'))
parent::init();
// custom initialization code goes here
}
Update
backend/config/main.php
'modules' => [
'authorization' => [
'class' => 'backend\modules\authorization\Authorization',
],
],
In your module class you can add this method
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (!\Yii::$app->user->can('admin')) {
throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page.');
}
return true;
}
In activerecord class i put this code
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
public function behaviors()
{
return [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['create_time'],
],
];
}
but it is throwing me an error
Invalid Configuration – yii\base\InvalidConfigException
Object configuration must be an array containing a "class" element.
I dont know where i am doing wrong . i also follow this link
TimestampBehavior is not working in Yii2
but this is also not solving my problem.
Here is the corrected version:
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['create_time'],
],
],
];
}
Here is deeper explanation.
The main problem is you forgot to wrap behavior config into its own array, that's why the error is thrown. This config as all others is processed by Yii::createObject() method. So you need array containing at least class element. In case you want default config you can omit this for brevity with just specifying class name, for example:
public function behaviors()
{
return [
TimestampBehavior::className(),
],
];
}
Besides that, you also forgot to close square bracket after attribute.
And finally, you should not specify attributes like that. It was like that at initial stage of this behavior, then it was refactored. Now you only need to specify according attribute names, for example:
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at', // This is by default, you can omit that
'updatedAtAttribute' => 'updated_at', // This is by default, you can omit that
],
],
];
}
Also I don't think that having the same column for tracking create and update time is a good idea.
Additionally you can specify value used to update these columns:
use yii\db\Expression;
...
'value' => new Expression('NOW()'),
This will involve database to calculate time, if you want to do it on server side via PHP, you can do use closure for example like this:
'value' => function () {
return date('Y-m-d H:i:s');
}
And one more thing even if it's not directly related with this problem - you can set alias for every behavior by setting a key of configuration array. This is called named behavior:
public function behaviors()
{
return [
'timestamp' => [
...
],
],
];
}
This was mentioned by #GAMITG in his answer.
You can try this code.
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['create_time'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['create_time'],
],
],
];
}