exmr/lib/exmr_web/live/exam_live/form_component.ex

87 lines
2.4 KiB
Elixir
Raw Normal View History

2024-11-14 23:33:29 +02:00
defmodule ExmrWeb.ExamLive.FormComponent do
use ExmrWeb, :live_component
alias Exmr.Exams
@impl true
def render(assigns) do
~H"""
<div>
<.header>
<%= @title %>
<:subtitle>
<%= gettext("Use this form to manage exam records in your database.") %>
</:subtitle>
2024-11-14 23:33:29 +02:00
</.header>
<.simple_form
for={@form}
id="exam-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<.input field={@form[:subject]} type="text" label={gettext("Subject")} />
<.input field={@form[:description]} type="text" label={gettext("Description")} />
<.input field={@form[:date]} type="date" label={gettext("Date")} />
2024-11-14 23:33:29 +02:00
<:actions>
<.button phx-disable-with={gettext("Saving...")}><%= gettext("Save Exam") %></.button>
2024-11-14 23:33:29 +02:00
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(%{exam: exam} = assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_new(:form, fn ->
to_form(Exams.change_exam(exam))
end)}
end
@impl true
def handle_event("validate", %{"exam" => exam_params}, socket) do
changeset = Exams.change_exam(socket.assigns.exam, exam_params)
{:noreply, assign(socket, form: to_form(changeset, action: :validate))}
end
def handle_event("save", %{"exam" => exam_params}, socket) do
save_exam(socket, socket.assigns.action, exam_params)
end
defp save_exam(socket, :edit, exam_params) do
case Exams.update_exam(socket.assigns.exam, exam_params) do
{:ok, exam} ->
notify_parent({:saved, exam})
{:noreply,
socket
|> put_flash(:info, "Exam updated successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, form: to_form(changeset))}
end
end
defp save_exam(socket, :new, exam_params) do
case Exams.create_exam(exam_params) do
{:ok, exam} ->
notify_parent({:saved, exam})
{:noreply,
socket
|> put_flash(:info, "Exam created successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, form: to_form(changeset))}
end
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
end