简体   繁体   中英

CakePHP Redirect method not working?

We started following the CakePHP Blog tutorial hosted on the website cakephp.org - http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html

At this point we're stuck on the redirecting after submitting a form (ie function edit / add). This is how our code looks like:

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($this->referer());
        } else {
            $this->Session->setFlash('Unable to update your post.');
        }
    }
}

After commenting the line $this->redirect($this->referer()); the page is refering to his own... with the line added it'll stay on a empty white page.

Example: http://www.drukwerkprijsvergelijk.nl/posts/

Please help this little kittens, we're desperate.

you cannot use referer() on edit. thats because after the first POST the referer is the same page as you are on right now. referer() can only be used for redirects if there was no form post on this page (delete for example or edit/add right after accessing the page). but even with delete() you must be careful. coming from "view" would result the redirect to run into a redirect loop...

you can store the referer in the form as hidden field and use this to redirect back.

For the reasons mark explained above, you can't use referer() on edit and add.

Use something like

$this->redirect(array('action' => 'view', $id));

or

$this->redirect(array('action' => 'index'));

instead.

You can also try specifying the controller in the url array:

$this->redirect(array('controller' => 'posts', 'action' => 'index'));

Do you have any whitespace outside the PHP code in your PostController or your AppController ? I just looked at the source code of your edit page and it seems to contain a space character. This could prevent the headers to be set, thus preventing the redirect to work.

Use this one in before filter function

    header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // // HTTP/1.1
    header("Pragma: no-cache");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM