Vizualni
Vizualni

Reputation: 381

How to redirect if controller wasn't found? (cakephp)

This is my routes file. How can I redirect to array('controller' => 'pages', 'action' => 'display', 'home') if controller wasn't found?

Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
Router::connect('/login', array("controller"=>"user","action"=>"login"));
Router::connect('/settings', array("controller"=>"user","action"=>"settings"));
Router::connect('/logout', array("controller"=>"user","action"=>"logout"));
Router::connect('/video', array("controller"=>"video","action"=>"index"));
Router::connect('/video/page/*', array("controller"=>"video","action"=>"page"));
Router::connect('/video/*', array("controller"=>"video","action"=>"view")); 
Router::connect('/upcoming', array("controller"=>"user","action"=>"upcoming"));

Upvotes: 0

Views: 6043

Answers (3)

Barry Chapman
Barry Chapman

Reputation: 6780

This is pretty simple. Create an app_error.php file in your /app directory, (just the way you would for app_model.php or app_controller.php)

Once that is done, put in the following:

<?php
class AppError extends ErrorHandler {


    function missingController($params) {
        extract($params, EXTR_OVERWRITE);

        $this->controller->redirect('/');
    }    


}

Now, this should solve your problem. If you need to invoke components and beforeFilters/Renders, you can call those from the constructor.

Upvotes: 1

jack
jack

Reputation: 473

What you need is here explained neatly and working great>Hope this will help you.

OR

Go HERE

Upvotes: 1

Oldskool
Oldskool

Reputation: 34877

You should create a custom Exception handler that will redirect the user back ot the homepage. See the documentation on this topic.

Probably something like this (untested, but just to give you an idea where to go from here):

class AppErrorHandler {
    public static function handleException($error) {
        if ($error instanceof MissingControllerException) {
            // Redirect home, $this->redirect will probably not work,
            // since the Error Handler doesn't extend the AppController.
            header('Location: /');
            exit;
        }
    }
}

Upvotes: 1

Related Questions