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

73 lines
2.0 KiB
Elixir
Raw Normal View History

2022-07-25 20:12:11 -04:00
defmodule MemexWeb.PipelineLive.FormComponent do
use MemexWeb, :live_component
alias Memex.Pipelines
@impl true
2022-11-24 14:31:16 -05:00
def update(%{pipeline: pipeline, current_user: current_user} = assigns, socket) do
changeset = Pipelines.change_pipeline(pipeline, current_user)
2022-07-25 20:12:11 -04:00
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)}
end
@impl true
2022-11-24 14:31:16 -05:00
def handle_event(
"validate",
%{"pipeline" => pipeline_params},
%{assigns: %{pipeline: pipeline, current_user: current_user}} = socket
) do
2022-07-25 20:12:11 -04:00
changeset =
2022-11-24 14:31:16 -05:00
pipeline
|> Pipelines.change_pipeline(pipeline_params, current_user)
2022-07-25 20:12:11 -04:00
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
2022-11-24 14:31:16 -05:00
def handle_event(
"save",
%{"pipeline" => pipeline_params},
%{assigns: %{action: action}} = socket
) do
save_pipeline(socket, action, pipeline_params)
2022-07-25 20:12:11 -04:00
end
2022-11-24 14:31:16 -05:00
defp save_pipeline(
%{assigns: %{pipeline: pipeline, return_to: return_to, current_user: current_user}} =
socket,
:edit,
pipeline_params
) do
case Pipelines.update_pipeline(pipeline, pipeline_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:12:11 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} saved", slug: slug))
2022-11-24 14:31:16 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:12:11 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
2022-11-24 14:31:16 -05:00
defp save_pipeline(
%{assigns: %{return_to: return_to, current_user: current_user}} = socket,
:new,
pipeline_params
) do
case Pipelines.create_pipeline(pipeline_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:12:11 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} created", slug: slug))
2022-11-24 14:31:16 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:12:11 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end