0

Instead of showing an error page I'd like to redirect the user to the start page in general, if the route is invalid (there is no controller/action like requested). To make it sound the redirection should only happen on 'normal' page requests. Though AJAX calls can be invalid as well, I don't want to send a redirect to the browser here.

How can I do this efficiently?

Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
robsch
  • 9,358
  • 9
  • 63
  • 104

1 Answers1

3

You can override ErrorAction class and will implement necessary logic. For example:

class MyErrorAction extends \yii\web\ErrorAction
{

    public $redirectRoute;  

    public function run()
    {
        if (!Yii::$app->getRequest()->getIsAjax()) {
            Yii::$app->getResponse()->redirect($this->redirectRoute)->send();
            return;
        }
        return parent::run();
    }
}

After it, you should add this action in a controller and configure it

class SiteController
{
    public function actions()
    {
        return [
            'error' => [
                'class' => MyErrorAction::class
                'redirectRoute' => 'site/my-page'
            ],
        ];
    }
}

and configure the route of error action in the error handler

'errorHandler' => [
    'errorAction' => 'site/error',
]
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31