defmodule PrymnWeb.UserRegistrationLive do use PrymnWeb, :live_view alias Prymn.Accounts alias Prymn.Accounts.User @impl true def render(assigns) do ~H"""
<.header class="text-center"> Register for an account <:subtitle> Already registered? <.link navigate={~p"/auth/log_in"} class="text-brand font-semibold hover:underline"> Sign in to your account now. <.simple_form for={@form} id="registration_form" phx-submit="save" phx-change="validate" phx-trigger-action={@trigger_submit} action={~p"/auth/log_in?_action=registered"} method="post" > <.error :if={@check_errors}> Oops, something went wrong! Please check the errors below. <.input field={@form[:email]} type="email" label="Email" phx-debounce required /> <.input field={@form[:password]} type="password" label="Password" phx-debounce required /> <:actions> Create an account
""" end @impl true def mount(_params, _session, socket) do changeset = Accounts.change_user_registration(%User{}) socket = socket |> assign(trigger_submit: false, check_errors: false) |> assign_form(changeset) {:ok, socket, 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} -> {:ok, _} = Accounts.deliver_user_confirmation_instructions( user, &url(~p"/auth/confirm/#{&1}") ) changeset = Accounts.change_user_registration(user) {:noreply, socket |> assign(trigger_submit: true) |> assign_form(changeset)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, socket |> assign_form(changeset) |> assign(check_errors: true)} end end @impl true def handle_event("validate", %{"user" => user_params}, socket) do changeset = Accounts.change_user_registration(%User{}, user_params) {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))} end defp assign_form(socket, %Ecto.Changeset{} = changeset) do assign(socket, form: to_form(changeset, as: "user")) end end