Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect back to previous page after invalid input

I currently have the code below in a controller helper module. It allows me to redirect back to the previous page by grabbing the the conn's referrer. The problem with this is if there is a invalid input on a form for example, the conn's referrer is reset to the current page.

  def redirect_back(conn, alternative \\ "/") do
    path = conn
    |> get_req_header("referer")
    |> referrer
    path || alternative
  end

 defp referrer([]), do: nil
 defp referrer([h|_]), do: h

How can I hold the referrer to the correct previous page so I can use it to redirect even if something like an invalid input occurs?

like image 444
Joe Rocca Avatar asked Oct 12 '16 18:10

Joe Rocca


1 Answers

There was a discussion in phoenix issues on the topic, that resulted in the fancy small library that you might want to include into your project and use like this:

def redirect_back(conn, alternative \\ "/") do
  conn |> NavigationHistory.last_path(default: alternative)
end

or in any other way, described in it’s README/help.

like image 181
Aleksei Matiushkin Avatar answered Oct 19 '22 07:10

Aleksei Matiushkin