We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Dispatcher->forward does nothing

I have a component configured as a beforeDispatch listener. This component checks if a form was POSTed, then checks that the CSRF token was properly sent. If not, it is supposed to forward to a special CSRF notification page. I specifically want to do a forward and not a redirect so that users have the option of reporting which page they visited.

Here is my code:

public function beforeDispatch(\Phalcon\Events\Event $Event,\Phalcon\Mvc\Dispatcher $Dispatcher){
    if($this->request->isPost()){
        if(!$this->checkToken()){
            echo 'before';
            $Dispatcher->forward(['controller'=>'index','action'=>'csrf']);
            echo 'after';
            exit();
        }
    }
}

All I get is a page that displays "beforeafter". If I take those echos out, I just get a blank page. I can visit /index/csrf/ manually and it displays the page I want.

Why is the request not getting forwarded? Is this out of the dispatch loop?



4.0k
edited Nov '17

Ordinary I call the forward method from inside a controller, and i use it with a return instruction.

Like this :

return $Dispatcher->forward(['controller'=>'index','action'=>'csrf']);

I don't know if it will work

in the controllers I use the dispacher in the DI, use forward() and simpply return false

class ControllerBase extends Phalcon\Mvc\Controller {

    public function beforeExecuteRoute($dispatcher) {
        $this->dispatcher->forward(
                array(
                    'controller' => 'Login',
                    'action' => 'index'
                )
        );
        return false;
    }

}


125.7k
Accepted
answer
edited Nov '17

Both returning the result of $Dispatcher->forward, and FALSE resulted in a cyclic routing exception. So, I added a condition to not forward if I'm already at the CSRF page, and removed my exit(). It now works - I don't need to return anything.

Thanks for the replies.