3
votes

I have an action, /controller/edit, which can be clicked to from multiple locations (e.g. /controller/index and /controller/view).

Once the user has finished editing the record and clicks save, I want them to return to wherever they came from (/controller/index or /controller/view respectively).

At first I tried storing each page the user visits in their session (e.g. home > index > edit), and then redirecting to the second-to-last entry in that list - and that works fine right up until they open another tab. If, while they're editing the record they open another tab and go off somewhere else, their session variable keeps being built on (home > index > edit > help > help page), and when the time comes to redirect the second-to-last entry no longer contains the correct action.

How can my edit action /controller/edit, on save, redirect the user back to the referring page they came from to get there, independent of whatever the user has done in other tabs?

Edit: I can't use referrer after save because the process is this:

  1. User is on either /controller/index or /controller/view
  2. User clicks into /controller/edit (referrer is /controller/index or /controller/view)
  3. User makes changes to record and clicks save, which form submits to /controller/edit (referrer is /controller/edit)
  4. I now want to redirect them to either /controller/index or /controller/view, but that is no longer in the referrer
4

4 Answers

6
votes

Use to return to wherever you came from

return $this->redirect($this->referer());
5
votes

I had to deal with the same problem and I did this:

1) In my controller, in the GET section, set the referer to a view variable like this:

$this->set('redirect', $this->referer());

2) In the form, set a hidden control named "redirect":

echo $this->Form->hidden('redirect', ['value' => $redirect]);

3) In the controller, after processing the POST request, redirect to the value of the hidden input:

if (isset($this->request->data['redirect'])) {
    $this->redirect($this->request->data['redirect']);
}

Of couse, this could be abstracted into a component and maybe use session, but this approach worked for me.

1
votes

You can redirect to the referring page, using return $this->redirect($this->referer());

As per the Documentation it will redirect you to the referring page.

0
votes

This is extension to @DanielCoturel answer. Step 1. in his answer is redundant (see my comment). I did it more globally by overwriting redirect() function in AppController.php (still have to add 'redirect' input to all forms):

public function redirect($url, $status = 302)
    {
        if ($this->request->getData('redirect', '')) {
            return parent::redirect($this->request->getData('redirect'), $status);
        }
        return parent::redirect($url, $status);
    }