0

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?

1 Answer 1

2

The method will issue an exit() after the redirect unless you set the third parameter to false.

In this case, setFlash adds your message to the session, which can then be displayed in your view when the page you redirect to loads. By default redirect calls exit, so anything you put after it will never get executed. Even if you set the third parameter to false, the behaviour of setFlash would 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 flash method on the controller instead (note that the message would have a full page of its own):

Like redirect(), the flash() method is used to direct a user to a new page after an operation. The flash() method is different in that it shows a message before passing the user on to another URL.

The first parameter should hold the message to be displayed, and the second parameter is a CakePHP-relative URL. CakePHP will display the $message for $pause seconds before forwarding the user on.

If there’s a particular template you’d like your flashed message to use, you may specify the name of that layout in the $layout parameter.

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.

$this->flash('Your post has been updated.', array('action' => 'index'), 5);

http://book.cakephp.org/2.0/en/controllers.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.