-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathitem_controller.ex
79 lines (65 loc) · 1.82 KB
/
item_controller.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
defmodule AppWeb.ItemController do
use AppWeb, :controller
alias App.Todo
alias App.Todo.Item
def index(conn, params) do
item = if not is_nil(params) and Map.has_key?(params, "id") do
Todo.get_item!(params["id"])
else
%Item{}
end
items = Todo.list_items()
changeset = Todo.change_item(item)
render(conn, "index.html", items: items, changeset: changeset, editing: item)
end
def new(conn, _params) do
changeset = Todo.change_item(%Item{})
render(conn, :new, changeset: changeset)
end
def create(conn, %{"item" => item_params}) do
case Todo.create_item(item_params) do
{:ok, _item} ->
conn
|> put_flash(:info, "Item created successfully.")
|> redirect(to: ~p"/items/")
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, :new, changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
item = Todo.get_item!(id)
render(conn, :show, item: item)
end
def edit(conn, params) do
index(conn, params)
end
def update(conn, %{"id" => id, "item" => item_params}) do
item = Todo.get_item!(id)
case Todo.update_item(item, item_params) do
{:ok, _item} ->
conn
|> redirect(to: ~p"/items/")
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, :edit, item: item, changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
item = Todo.get_item!(id)
{:ok, _item} = Todo.delete_item(item)
conn
|> put_flash(:info, "Item deleted successfully.")
|> redirect(to: ~p"/items")
end
def toggle_status(item) do
case item.status do
1 -> 0
0 -> 1
end
end
def toggle(conn, %{"id" => id}) do
item = Todo.get_item!(id)
Todo.update_item(item, %{status: toggle_status(item)})
conn
|> redirect(to: ~p"/items")
end
end