user2382627
user2382627

Reputation:

cakephp - how to redirect in a Component

I created a Component and in this component I try to redirect to a different controller/action, but I get the error: "Error: Call to undefined method SessionRestComponent::redirect()"

My Component code:

function iniciaSessao($username=''){
                 $_SESSION['username'] = $username;
                                //  debug(isset($_SESSION['username']));
                                if (isset($_SESSION['username'])) {
                                    $this->redirect(array('controller' => 'registos', 'action' => 'indexUser'));
                                }
            }

Anyone can help me?

Upvotes: 1

Views: 4633

Answers (2)

ahmyi
ahmyi

Reputation: 31

For those using Cakephp 3 here's a link. Where inside the component

function iniciaSessao($username=''){
     ...
     $this->_registry->getController()->redirect($url);
}

Upvotes: 3

mark
mark

Reputation: 21743

You need to get the controller - for example in initialize() or startup() Then redirect using this controller.

public function startup(Controller $controller) {
    $this->Controller = $controller;
}

public function iniciaSessao() {
    ...
    $this->Controller->redirect($url);
}

and do not use $_SESSION directly, use $this->Session component as documented. You just need to add the component to your custom component:

public $components = array('Session');

Upvotes: 7

Related Questions