cola
cola

Reputation: 12486

CakePHP redict to other url from view

I want to redirect to other view from view.ctp .

Suppose like this =>

if($val == 0 ) {
  redirec to 'posts/index'
}

How can i do this ?

Upvotes: 0

Views: 149

Answers (1)

deceze
deceze

Reputation: 522626

You do redirection in the controller, not in the view. Period.
You can do the same check you're doing in the view in the controller easily.

I don't know about your specific situation, but I usually use this pattern:

public function view($id) {
    $post = $this->Post->find('first', array(
        'conditions' => array('Post.id' => $id, 'Post.mark' => 1)
    ));
    if (!$post) {
        $this->cakeError('error404');
        // or redirect, or show a more specific error page, or do something else
    }

    $this->set(compact('post'));
}

This way the check you need to do is handled on the database level, were it belongs, and the redirect/error is handled in the controller, were it belongs. The view is much too late in the request cycle to check for business logic like "is the user actually allowed to see this?", the job of the view is only to output information.

Upvotes: 1

Related Questions