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