56 lines
1.4 KiB
Elixir
56 lines
1.4 KiB
Elixir
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
|
|
|> put_flash(:info, "Note updated successfully")
|
|
|> push_navigate(to: socket.assigns.return_to)}
|
|
|
|
{: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
|
|
|> put_flash(:info, "Note created successfully")
|
|
|> push_navigate(to: socket.assigns.return_to)}
|
|
|
|
{:error, %Ecto.Changeset{} = changeset} ->
|
|
{:noreply, assign(socket, changeset: changeset)}
|
|
end
|
|
end
|
|
end
|