I have the standard, auto-generated form-component or modal of LiveView. I’m using a modal in a part of a website where only authenticated users are allowed. I assign “current_user” to session variable in a plug.
router:
live_session :on_authenticated, on_mount: MyWebsiteWeb123.InitLiveAssigns do
scope "/", MyWebsiteWeb123 do
pipe_through :browser
live "/abc", MyLive
end
end
init assigns module:
defmodule MyWebsiteWeb123.InitLiveAssigns do
import Phoenix.LiveView
def on_mount(:on_authenticated, _params, session, socket) do
cu = Repo.get!(User, session["current_user_id"])
socket2 = assign(socket, :current_user, cu)
{:cont, socket2}
end
end
This nicely allows me to get access to the current_user
in socket in the situations when “submit” button is clicked, in a normal form on a page.
However, not in a modal. That is, not when “save” button is clicked in it – ‘current_user’ gets dissapered.
//current user is nil
def handle_event("save", %{"my_model" => my_model_params}, socket) do
// 'current_user' doesn't exist anywhere in 'socket'
a1 = socket.assings[:current_user]
//
//a2 = socket.assings[:current_user_id]
//a3 = socket.assings["current_user"]
//a4 = socket.assings["current_user_id"]
//a5 = socket["current_user_id"]
//a6 = ...........
//......
end
Where has current_user
has disappered from assigns in a modal?
How to make all this work?