3

I have a route set up in routes.php that calls a controller action using something similar to what is described here: https://straightupcraft.com/articles/how-do-i-setup-a-route-to-point-to-a-controller-action-instead-of-a-template

This works much better for my purposes than POSTing a form to the controller. However, I'm not sure how best to handle redirects. Ideally I would like to redirect back to the page where the user clicked on the link, but calling

$this->redirectToPostedUrl()

doesn't work when using a route like this. The URL just remains the URL as defined in the route.

Is there a different method I can use to make sure users are returned to the page where they were when they clicked the link?

3

You're mistaken about how redirectToPostedUrl works... That's designed to redirect from a form submission, when the redirect field was supplied:

<input type="hidden" name="redirect" value="page/to/redirect/to"> 

What you really want is this:

$this->redirect(craft()->request->getUrlReferrer());

The request->getUrlReferrer method will actually retrieve the originating page URL.

| improve this answer | |
  • Yup, I knew redirectToPostedUrl wasn't what I needed, but just wasn't quite sure where to turn. This looks like exactly what I needed though, thank you! – John O Oct 14 '15 at 23:54
  • Cool, no problem! :) – Lindsey D Oct 14 '15 at 23:58
  • Note that request->getUrlReferrer actually uses the request headers from the browser, so you cannot assume that it exists and/or is reliable 100% of the time. To ensure you redirect back to the appropriate page you will need to include that hidden "redirect" input in your form. – Jordan Lev Jun 20 '17 at 21:59
1

In case you need this for CraftCMS version 3, as I did today, the code slightly changed:

$this->redirect(Craft::$app->getRequest()->referrer);

This works fine with version 3.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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