defmodule HomemanWeb.TaskLive.FormComponent do use HomemanWeb, :live_component alias Homeman.Accounts @impl true def render(assigns) do ~H"""
<.header> <%= @title %> <:subtitle>Use this form to manage task records in your database. <.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
""" 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