memEx/lib/memex_web/live/step_live/form_component.ex

84 lines
2.2 KiB
Elixir
Raw Normal View History

2022-11-26 21:26:21 -05:00
defmodule MemexWeb.StepLive.FormComponent do
use MemexWeb, :live_component
2023-03-18 23:03:15 -04:00
alias Ecto.Changeset
2022-11-26 21:26:21 -05:00
alias Memex.Pipelines.Steps
@impl true
def update(%{step: step, current_user: current_user, pipeline: _pipeline} = assigns, socket) do
changeset = Steps.change_step(step, current_user)
2023-03-18 23:03:15 -04:00
socket =
socket
|> assign(assigns)
|> assign(:changeset, changeset)
{:ok, socket}
2022-11-26 21:26:21 -05:00
end
@impl true
def handle_event(
"validate",
%{"step" => step_params},
%{assigns: %{step: step, current_user: current_user}} = socket
) do
2023-03-18 23:03:15 -04:00
changeset = step |> Steps.change_step(step_params, current_user)
2022-11-26 21:26:21 -05:00
changeset =
2023-03-18 23:03:15 -04:00
case changeset |> Changeset.apply_action(:validate) do
{:ok, _data} -> changeset
{:error, changeset} -> changeset
end
2022-11-26 21:26:21 -05:00
{:noreply, assign(socket, :changeset, changeset)}
end
def handle_event("save", %{"step" => step_params}, %{assigns: %{action: action}} = socket) do
save_step(socket, action, step_params)
end
defp save_step(
%{assigns: %{step: step, return_to: return_to, current_user: current_user}} = socket,
:edit_step,
step_params
) do
2023-03-18 23:03:15 -04:00
socket =
case Steps.update_step(step, step_params, current_user) do
{:ok, %{title: title}} ->
socket
|> put_flash(:info, gettext("%{title} saved", title: title))
|> push_navigate(to: return_to)
2022-11-26 21:26:21 -05:00
2023-03-18 23:03:15 -04:00
{:error, %Changeset{} = changeset} ->
assign(socket, :changeset, changeset)
end
{:noreply, socket}
2022-11-26 21:26:21 -05:00
end
defp save_step(
%{
assigns: %{
step: %{position: position},
return_to: return_to,
current_user: current_user,
pipeline: pipeline
}
} = socket,
:add_step,
step_params
) do
2023-03-18 23:03:15 -04:00
socket =
case Steps.create_step(step_params, position, pipeline, current_user) do
{:ok, %{title: title}} ->
socket
|> put_flash(:info, gettext("%{title} created", title: title))
|> push_navigate(to: return_to)
{:error, %Changeset{} = changeset} ->
assign(socket, changeset: changeset)
end
2022-11-26 21:26:21 -05:00
2023-03-18 23:03:15 -04:00
{:noreply, socket}
2022-11-26 21:26:21 -05:00
end
end