zen of coding

Food for thought: $this->redirect() vs $this->render()

One example, that we often see, is something along the following lines in the controller:

if($this->User->save($this->data)) {
  $this->Session->setFlash(... some stuff for the view ... );
  $this->redirect(array('action'=>'success'));
}

If all we are doing is displaying a “success” page back to the user, do we really need to bother with a redirect()?

To me it seems a little easier to do:

if($this->User->save($this->data)) {
  $this->set('arrayOfMessages', $myPreviouslyPreparedArrayOfMessages);
  $this->render('success');
}

Not really a big deal one way or another, but something to consider (especially for those very high traffic servers ;)).

P.S. As some readers pointed out, the obvious draw back is that $this->render() will cause the data re-submit prompts when refreshing or going back in the browser.

  • Adam

    Beware that your method will start showing “are you sure you want to POST this data again?” messages whenever you use the browser’s refresh or back/forward buttons.

  • jetpac

    The advantage of a redirect over a call to render is that the form data is cleared so if the user hits refresh the form will not be submitted again.

    http://en.wikipedia.org/wiki/Post/Redirect/Get

  • teknoid

    @Adam, jetpac

    Thanks, that’s a very good point. I’ve updated the post to mention that.

  • Arif

    How i can pass parameter by cakephp render

  • @Arif

    As always, with $this->set()

  • Madhu

    like wts the use of this->render..
    i am new to cake…

  • @Madhu

    Please read the manual or look at the API

%d bloggers like this: