defmodule MyAppWeb.ChangePasswordComponent do
@moduledoc """
LiveComponent for changing the current user's password.
"""
use MyAppWeb, :live_component
@impl true
def render(assigns) do
~H"""
<.simple_form
for={@form}
class="mt-6"
id="user-password-change-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<.input field={@form[:current_password]} type="password" label="Current Password" />
<.input field={@form[:password]} type="password" label="New Password" />
<.input field={@form[:password_confirmation]} type="password" label="Confirm New Password" />
<:actions>
<.button phx-disable-with="Saving...">Save
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_form()}
end
@impl true
def handle_event("validate", %{"user" => user_params}, socket) do
{:noreply, assign(socket, form: AshPhoenix.Form.validate(socket.assigns.form, user_params))}
end
@impl true
def handle_event("save", %{"user" => user_params}, %{assigns: assigns} = socket) do
case AshPhoenix.Form.submit(assigns.form, params: user_params) do
{:ok, _user} ->
# TODO: Send email notification!
assigns.on_saved.()
{:noreply, socket}
{:error, form} ->
{:noreply, assign(socket, form: form)}
end
end
defp assign_form(%{assigns: %{current_user: user}} = socket) do
form = AshPhoenix.Form.for_update(user, :change_password, as: "user", actor: user)
assign(socket, form: to_form(form))
end
end