I'm trying to implement different languages in the app. So what I've done is created lang variable in Session in the db, which keeps the current selected language.
The problem is that i'm calling and updating the value through update action:
def update(conn, %{"id" => id, "session" => session_params}) do
session = Repo.get!(Session, id)
changeset = Session.changeset(session, session_params)
case Repo.update(changeset) do
{:ok, _session} ->
conn
|> put_flash(:info, "Session updated successfully.")
|> redirect(to: page_path(conn, :tableshow))
{:error, changeset} ->
render(conn, "edit.html", session: session, changeset: changeset)
end
end
, which redirects it to the specific path(here: page_path). My question: is it possible to get the current path and redirect to it, once the action is called? So then, when you change language it's not just redirects you to one specific page all the time, instead it just reloads the current page, where the action was called? Language selectors are in header in every page.So i want the page just to reload.Any suggestions?
Additional info: I'm calling the action from the app.html.eex like this
<%= render Pos1.SessionView, "session_en.html", changeset: @changesetlang, action: session_path(@conn, :update, @session) %>
where session_en.html is:
<%= form_for @changeset, @action, fn f -> %>
<%= hidden_input f, :lang, value: "1" %>
<%= submit "EN", class: "btn btn-primary" %>
<% end %>
One way to do this is to add another hidden_input
with the current page's URL, and redirect to that from the update
action.
In app.html.eex
, change the render
call to pass @conn
as conn
:
<%= render Pos1.SessionView, "session_en.html", changeset: @changesetlang, action: session_path(@conn, :update, @session), conn: @conn %>
then add the new hidden_input
to session_en.html.eex
<%= form_for @changeset, @action, fn f -> %>
<%= hidden_input f, :lang, value: "1" %>
<%= hidden_input f, :redirect_to, value: @conn.request_path %>
<%= submit "EN", class: "btn btn-primary" %>
<% end %>
and finally, in the controller, change the redirect
call to:
|> redirect(to: session_params["redirect_to"])
Edit: You probably want to restrict the redirect_to
to point only to your site. You can do that with a simple case
:
redirect_to = case session_params["redirect_to"] do
path = "/" <> _ -> path
_ -> "/some/default/path"
end
and then
|> redirect(to: redirect_to)
Thank you Scott S. for pointing this out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With