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

68 lines
1.8 KiB
Elixir
Raw Normal View History

2022-07-25 20:08:40 -04:00
defmodule MemexWeb.NoteLive.FormComponent do
use MemexWeb, :live_component
alias Memex.Notes
@impl true
2022-11-17 22:38:52 -05:00
def update(%{note: note, current_user: current_user} = assigns, socket) do
changeset = Notes.change_note(note, current_user)
2022-07-25 20:08:40 -04:00
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)}
end
@impl true
2022-11-17 22:38:52 -05:00
def handle_event(
"validate",
%{"note" => note_params},
%{assigns: %{note: note, current_user: current_user}} = socket
) do
2022-07-25 20:08:40 -04:00
changeset =
2022-11-17 22:38:52 -05:00
note
|> Notes.change_note(note_params, current_user)
2022-07-25 20:08:40 -04:00
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
2022-11-17 22:38:52 -05:00
def handle_event("save", %{"note" => note_params}, %{assigns: %{action: action}} = socket) do
save_note(socket, action, note_params)
2022-07-25 20:08:40 -04:00
end
2022-11-17 22:38:52 -05:00
defp save_note(
%{assigns: %{note: note, return_to: return_to, current_user: current_user}} = socket,
:edit,
note_params
) do
case Notes.update_note(note, note_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:08:40 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} saved", slug: slug))
2022-11-17 22:38:52 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:08:40 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
2022-11-17 22:38:52 -05:00
defp save_note(
%{assigns: %{return_to: return_to, current_user: current_user}} = socket,
:new,
note_params
) do
case Notes.create_note(note_params, current_user) do
2022-11-26 14:51:18 -05:00
{:ok, %{slug: slug}} ->
2022-07-25 20:08:40 -04:00
{:noreply,
socket
2022-11-26 14:51:18 -05:00
|> put_flash(:info, gettext("%{slug} created", slug: slug))
2022-11-17 22:38:52 -05:00
|> push_navigate(to: return_to)}
2022-07-25 20:08:40 -04:00
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end