To change default controller and action in Yii 2.0 put these two single line codes into correct location:
Change Default Controller:
Each application has a default controller specified via the [[yii\base\Application::defaultRoute]]
property. When a request does not specify a route, the route specified by this property will be used. For [[yii\web\Application|Web applications]]
, its value is site
, while for [[yii\console\Application|console applications]]
, it is help
.
Therefore, if a URL is http://yourdomain.com
or http://yourdomain.com/index.php
, it means the site
controller will handle the request. To change this behaviour, change the default controller with the application configuration file which is web.php
in config
folder of your Yii 2.0 application:
1 2 3 | [ 'defaultRoute' => 'main', ] |
So your application configuration will look somewhat like:
1 2 3 4 5 6 7 8 9 10 11 | $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'defaultRoute' => 'main', 'components' => [ 'formatter' => [ 'dateFormat' => 'MM dd, yyyy', ] , ... |
Change Default Action:
An action method is a public method whose name starts with the word action. The return value of an action method represents the response data to be sent to end users. Each controller has a default action specified via the [[yii\base\Controller::defaultAction]]
property. When a route contains the controller ID only, it implies that the default action of the specified controller is requested which is by default set as index
. If you want to change the default value, simply override this property in the controller class, like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 | namespace app\controllers; use yii\web\Controller; class MainController extends Controller { public $defaultAction = 'home'; public function actionHome() { return $this->render('home'); } } |
So in this way you can easily change default controller and action in Yii 2.0.
How can I change defaultController in Yii2.0 Advanced?
hi @mayank
you need to set it in backend/config/main.php
$config = [
…
‘components’ => [
…
],
‘params’ => $params,
‘defaultRoute’ => ‘user/index’,
];