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

69 lines
1.9 KiB
Elixir
Raw Normal View History

2022-07-25 20:11:08 -04:00
defmodule MemexWeb.ContextLive.FormComponent do
use MemexWeb, :live_component
alias Memex.Contexts
@impl true
2022-11-24 12:44:34 -05:00
def update(%{context: context, current_user: current_user} = assigns, socket) do
changeset = Contexts.change_context(context, current_user)
2022-07-25 20:11:08 -04:00
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)}
end
@impl true
2022-11-24 12:44:34 -05:00
def handle_event(
"validate",
%{"context" => context_params},
%{assigns: %{context: context, current_user: current_user}} = socket
) do
2022-07-25 20:11:08 -04:00
changeset =
2022-11-24 12:44:34 -05:00
context
|> Contexts.change_context(context_params, current_user)
2022-07-25 20:11:08 -04:00
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
2022-11-24 12:44:34 -05:00
def handle_event("save", %{"context" => context_params}, %{assigns: %{action: action}} = socket) do
save_context(socket, action, context_params)
2022-07-25 20:11:08 -04:00
end
2022-11-24 12:44:34 -05:00
defp save_context(
%{assigns: %{context: context, return_to: return_to, current_user: current_user}} =
socket,
:edit,
context_params
) do
case Contexts.update_context(context, context_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:11:08 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} saved", slug: slug))
2022-11-24 12:44:34 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:11:08 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
2022-11-24 12:44:34 -05:00
defp save_context(
%{assigns: %{return_to: return_to, current_user: current_user}} = socket,
:new,
context_params
) do
case Contexts.create_context(context_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:11:08 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} created", slug: slug))
2022-11-24 12:44:34 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:11:08 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end