homeman-elixir/lib/homeman_web/live/todo_live/form_component.ex
2024-01-21 23:48:10 -06:00

93 lines
2.4 KiB
Elixir

defmodule HomemanWeb.TodoLive.FormComponent do
use HomemanWeb, :live_component
alias Homeman.Accounts
@impl true
def render(assigns) do
~H"""
<div>
<.header>
<%= @title %>
<:subtitle>Use this form to manage todo records in your database.</:subtitle>
</.header>
<.simple_form
for={@form}
id="todo-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<.input field={@form[:description]} type="text" label="Description" />
<.input field={@form[:emoji]} type="text" label="Emoji" />
<.input field={@form[:completed_at]} type="datetime-local" label="Completed at" />
<:actions>
<.button phx-disable-with="Saving...">Save Todo</.button>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(%{todo: todo} = assigns, socket) do
changeset = Accounts.change_todo(todo)
{:ok,
socket
|> assign(assigns)
|> assign_form(changeset)}
end
@impl true
def handle_event("validate", %{"todo" => todo_params}, socket) do
changeset =
socket.assigns.todo
|> Accounts.change_todo(todo_params)
|> Map.put(:action, :validate)
{:noreply, assign_form(socket, changeset)}
end
def handle_event("save", %{"todo" => todo_params}, socket) do
save_todo(socket, socket.assigns.action, todo_params)
end
defp save_todo(socket, :edit, todo_params) do
case Accounts.update_todo(socket.assigns.todo, todo_params) do
{:ok, todo} ->
notify_parent({:saved, todo})
{:noreply,
socket
|> put_flash(:info, "Todo updated successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
defp save_todo(socket, :new, todo_params) do
case Accounts.create_todo(todo_params) do
{:ok, todo} ->
notify_parent({:saved, todo})
{:noreply,
socket
|> put_flash(:info, "Todo created successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
assign(socket, :form, to_form(changeset))
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
end