-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathform_component.ex
99 lines (83 loc) · 2.77 KB
/
form_component.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
defmodule CesiumLinkWeb.LinkLive.FormComponent do
use CesiumLinkWeb, :live_component
alias CesiumLink.Links
@impl true
def render(assigns) do
~H"""
<div>
<.header>
<%= @title %>
<:subtitle>
<%= gettext("Links appear as highlights on the home page of the app.") %>
</:subtitle>
</.header>
<.simple_form for={@form} id="link-form" phx-target={@myself} phx-change="validate" phx-submit="save">
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:emoji]} type="emoji" label="Emoji" />
<.input field={@form[:url]} type="text" label="URL" />
<.input field={@form[:attention]} type="checkbox" label="Attention" />
<%= if @action == :new do %>
<.input field={@form[:publish_at]} type="datetime-local" label="Publish At" />
<% end %>
<:actions>
<.button phx-disable-with="Saving...">Save Link</.button>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(%{link: link} = assigns, socket) do
changeset = Links.change_link(link)
{:ok,
socket
|> assign(assigns)
|> assign_form(changeset)}
end
@impl true
def handle_event("validate", %{"link" => link_params}, socket) do
changeset =
socket.assigns.link
|> Links.change_link(link_params)
|> Map.put(:action, :validate)
{:noreply, assign_form(socket, changeset)}
end
def handle_event("save", %{"link" => link_params}, socket) do
save_link(socket, socket.assigns.action, link_params)
end
defp save_link(socket, :edit, link_params) do
case Links.update_link(
socket.assigns.link,
link_params |> Map.put_new("edited_at", Timex.now())
) do
{:ok, link} ->
notify_parent({:saved, link})
{:noreply,
socket
|> put_flash(:info, "Link updated successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
defp save_link(socket, :new, link_params) do
case Links.create_link(
link_params
|> Map.put_new("index", Links.get_next_link_index())
|> Map.put_new("edited_at", Timex.now())
) do
{:ok, link} ->
notify_parent({:saved, link})
{:noreply,
socket
|> put_flash(:info, "Link created successfully")
|> push_patch(to: socket.assigns.patch)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
assign(socket, :form, to_form(changeset))
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
end