defmodule ChesstrainerWeb.UserLive.Registration do use ChesstrainerWeb, :live_view alias Chesstrainer.Accounts alias Chesstrainer.Accounts.User @impl true def render(assigns) do ~H"""
<.header> Register for an account <:subtitle> Already registered? <.link navigate={~p"/users/log-in"} class="font-semibold text-brand hover:underline"> Log in to your account now.
<.form for={@form} id="registration_form" phx-submit="save" phx-change="validate"> <.input field={@form[:username]} type="text" label="Username" autocomplete="username" spellcheck="false" required phx-mounted={JS.focus()} /> <.input field={@form[:email]} type="email" label="Email" autocomplete="email" spellcheck="false" required /> <.input field={@form[:password]} type="password" label="Password" autocomplete="new-password" spellcheck="false" required /> <.input field={@form[:password_confirmation]} type="password" label="Confirm password" autocomplete="new-password" spellcheck="false" required /> <.button phx-disable-with="Creating account..." class="btn btn-primary w-full"> Create an account
""" end @impl true def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket) when not is_nil(user) do {:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))} end def mount(_params, _session, socket) do changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false) {:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]} end @impl true def handle_event("save", %{"user" => user_params}, socket) do case Accounts.register_user(user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "Account created successfully. Please log in.") |> push_navigate(to: ~p"/users/log-in")} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign_form(socket, changeset)} end end def handle_event("validate", %{"user" => user_params}, socket) do changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false) {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))} end defp assign_form(socket, %Ecto.Changeset{} = changeset) do form = to_form(changeset, as: "user") assign(socket, form: form) end end