So in blog cakephp 2.0 tutorial, there are following lines
http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html
<?php
public function edit($id = null) {
$this->Post->id = $id;
if ($this->request->is('get')) {
$this->request->data = $this->Post->read();
} else {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
Why does $this->Session->setFlash(‘Your post has been updated.’); go before the redirect line? Once it gets redirected, why does the message get displayed and not let’s say vice versa. First redirect and then flash the message?
In this case,
setFlashadds your message to the session, which can then be displayed in your view when the page you redirect to loads. By defaultredirectcallsexit, so anything you put after it will never get executed. Even if you set the third parameter tofalse, the behaviour ofsetFlashwould not change.You would use this when you wanted the message to just be a small part of the page, like the ‘this post has been edited’ or ‘a new answer has been posted’ messages you get here on SO.
If you wanted to show the flash message before redirecting (ie. redirecting in HTML), you can use the
flashmethod on the controller instead (note that the message would have a full page of its own):A page showing your message will first be displayed, then it will automatically redirect a number of seconds afterwards. You can optionally pass a layout in as the fourth parameter, to have more control over its appearance.
http://book.cakephp.org/2.0/en/controllers.html