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

94 lines
2.5 KiB
Elixir

defmodule HomemanWeb.TaskLive.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 task records in your database.</:subtitle>
</.header>
<.simple_form
for={@form}
id="task-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" />
<.input field={@form[:phase]} type="text" label="Phase" />
<:actions>
<.button phx-disable-with="Saving...">Save Task</.button>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(%{task: task} = assigns, socket) do
changeset = Accounts.change_task(task)
{:ok,
socket
|> assign(assigns)
|> assign_form(changeset)}
end
@impl true
def handle_event("validate", %{"task" => task_params}, socket) do
changeset =
socket.assigns.task
|> Accounts.change_task(task_params)
|> Map.put(:action, :validate)
{:noreply, assign_form(socket, changeset)}
end
def handle_event("save", %{"task" => task_params}, socket) do
save_task(socket, socket.assigns.action, task_params)
end
defp save_task(socket, :edit, task_params) do
case Accounts.update_task(socket.assigns.task, task_params) do
{:ok, task} ->
notify_parent({:saved, task})
{:noreply,
socket
|> put_flash(:info, "Task updated successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
defp save_task(socket, :new, task_params) do
case Accounts.create_task(task_params) do
{:ok, task} ->
notify_parent({:saved, task})
{:noreply,
socket
|> put_flash(:info, "Task 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