Skip to content

Commit

Permalink
Auto save: update record on every change.
Browse files Browse the repository at this point in the history
  • Loading branch information
slashrsm committed Mar 16, 2020
1 parent 50709fd commit dde9925
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
31 changes: 31 additions & 0 deletions lib/phoenix_auto_save_web/live/post_form_live.ex
@@ -0,0 +1,31 @@
defmodule PhoenixAutoSaveWeb.PostFormLive do
use Phoenix.LiveView
use Phoenix.HTML

alias PhoenixAutoSave.Posts

def render(assigns) do
Phoenix.View.render(PhoenixAutoSaveWeb.PostView, "form.html", assigns)
end

def mount(_params, session, socket) do
{
:ok,
socket
|> assign(:changeset, session["changeset"])
|> assign(:post, session["post"])
|> assign(:action, session["action"])
}
end

def handle_event("change", %{"post" => post_params}, socket) do
{:ok, post} = Posts.update_post(socket.assigns.post, post_params)
{
:noreply,
socket
|> assign(:changeset, Posts.change_post(post))
|> assign(:post, post)
}
end

end
10 changes: 9 additions & 1 deletion lib/phoenix_auto_save_web/templates/post/edit.html.eex
@@ -1,5 +1,13 @@
<h1>Edit Post</h1>

<%= render "form.html", Map.put(assigns, :action, Routes.post_path(@conn, :update, @post)) %>
<%= live_render(
@conn,
PhoenixAutoSaveWeb.PostFormLive,
session: %{
"changeset" => @changeset,
"action" => Routes.post_path(@conn, :update, @post),
"post" => @post
}
) %>

<span><%= link "Back", to: Routes.post_path(@conn, :index) %></span>
@@ -1,4 +1,4 @@
<%= form_for @changeset, @action, fn f -> %>
<%= f = form_for @changeset, @action, phx_change: :change %>
<%= if @changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
Expand All @@ -16,4 +16,4 @@
<div>
<%= submit "Save" %>
</div>
<% end %>
</form>

0 comments on commit dde9925

Please sign in to comment.