Hi,
I find myself unable to submit form data to a controller with populated fields while using LiveView.
Here’s the form in a new LiveView project:
defmodule MyAppWeb.LoginLive do
use MyAppWeb, :live_view
def render(assigns) do
~H"""
<.form
let={f}
for={:user}
phx-submit="login"
method="post"
action={Routes.user_session_path(@socket, :create)}
phx-trigger-action={assigns[:login_valid]}>
<%= label f, :email %>
<%= email_input f, :email %>
<%= error_tag f, :email %>
<%= label f, :password %>
<%= password_input f, :password %>
<%= error_tag f, :password %>
<%= submit "Save" %>
</.form>
"""
end
def handle_event("login", _values, socket) do
{:noreply, assign(socket, login_valid: true)}
end
end
Here’s the controller:
defmodule MyAppWeb.UserSessionController do
use MyAppWeb, :controller
alias MyApp.Accounts
alias MyAppWeb.UserAuth
def create(conn, %{"user" => user_params}) do
%{"email" => email, "password" => password} = user_params
IO.inspect(user_params)
if user = Accounts.get_user_by_email_and_password(email, password) do
UserAuth.log_in_user(conn, user, user_params)
conn
|> redirect(to: Routes.some_path(conn, :index))
else
conn
|> put_flash(:error, "Invalid email or password")
|> redirect(to: Routes.live_path(conn, MyAppWeb.LoginLive))
end
end
end
When a login is attempted, the IO inspect within the controller create function prints the following:
%{"email" => "", "password" => ""}
However! When JavaScript is disabled on the client, the controller endpoint prints the form with populated values! How could this be?
I have added a bare repo which demonstrates this issue: GitHub - brettinternet/phx-trigger-action-formdata