YII2 defaultRoute - How to change default controller in template

  • Last update: Apr 3, 2024
  • Views: 41
  • Author: Admin
YII2 defaultRoute - How to change default controller in template

Colleagues hello to all.

In today's article, I'll show you how to change the default controller in Yii2 very quickly and easily.

 

By default, in Yii2, the SiteController.php file is the controller. We can verify this by looking at the debug tool.

yii2_default_route

As you can see in the screenshot, the Route value is site/index, which means that the default controller is set to site and the default action is set to index.


 

In order for us to change the default controller in Yii2 from site to something else, we need to set a parameter called defaultRoute in your site's web.php configuration file. In this example, I will make my default controller named main.

The first thing we need to do is create a new file in the controllers directory called MainController.php with the content:

namespace app\controllers;

use yii\web\Controller;

class MainController extends Controller
{

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

}

yii2_default_route


 

The next step is to set the defaultRoute parameter in the web.php configuration file

'defaultRoute' => 'main',

yii2_default_route

In the  defaultRoute parameter, we explicitly indicate that we want us to have a default controller called main, and the MainController.php file will be responsible for main


 

Now when we reload the page of our site, we will see in the debug tool that the Route parameter has changed from site to main.

yii2_default_route


 

Thank you all, I hope that my article helped you in some way.

SIMILAR ARTICLES