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

56 lines
1.5 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
def update(%{context: context} = assigns, socket) do
changeset = Contexts.change_context(context)
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)}
end
@impl true
def handle_event("validate", %{"context" => context_params}, socket) do
changeset =
socket.assigns.context
|> Contexts.change_context(context_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
def handle_event("save", %{"context" => context_params}, socket) do
save_context(socket, socket.assigns.action, context_params)
end
defp save_context(socket, :edit, context_params) do
case Contexts.update_context(socket.assigns.context, context_params) do
{:ok, _context} ->
{:noreply,
socket
2022-11-17 22:30:01 -05:00
|> put_flash(:info, "context updated successfully")
2022-11-16 21:11:02 -05:00
|> push_navigate(to: socket.assigns.return_to)}
2022-07-25 20:11:08 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
defp save_context(socket, :new, context_params) do
case Contexts.create_context(context_params) do
{:ok, _context} ->
{:noreply,
socket
2022-11-17 22:30:01 -05:00
|> put_flash(:info, "context created successfully")
2022-11-16 21:11:02 -05:00
|> push_navigate(to: socket.assigns.return_to)}
2022-07-25 20:11:08 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end