exmr/lib/exmr_web/live/exam_live/form_component.ex
Vladimir Rubin 9e9d8ffdaf
Some checks failed
Checks / check (pull_request) Failing after -6m8s
trans: settings and new exam modal
translated those to russian
2024-12-11 22:18:34 +02:00

86 lines
2.4 KiB
Elixir

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>
</.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")} />
<:actions>
<.button phx-disable-with={gettext("Saving...")}><%= gettext("Save Exam") %></.button>
</: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