forked from jimmykuu/gopher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
package_category.go
97 lines (78 loc) · 2.63 KB
/
package_category.go
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
package gopher
import (
"net/http"
"github.com/gorilla/mux"
"github.com/jimmykuu/wtforms"
"gopkg.in/mgo.v2/bson"
)
// URL: /admin/package_categories
// 列出所有的包分类
func adminListPackageCategoriesHandler(handler *Handler) {
var categories []PackageCategory
c := handler.DB.C(PACKAGE_CATEGORIES)
c.Find(nil).All(&categories)
handler.renderTemplate("admin/package_categories.html", ADMIN, map[string]interface{}{"categories": categories})
}
// URL: /admin/package_category/new
// 新建包分类
func adminNewPackageCategoryHandler(handler *Handler) {
defer dps.Persist()
form := wtforms.NewForm(
wtforms.NewTextField("id", "ID", "", wtforms.Required{}),
wtforms.NewTextField("name", "名称", "", wtforms.Required{}),
)
if handler.Request.Method == "POST" {
if !form.Validate(handler.Request) {
handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{"form": form})
return
}
c := handler.DB.C(PACKAGE_CATEGORIES)
var category PackageCategory
err := c.Find(bson.M{"name": form.Value("name")}).One(&category)
if err == nil {
form.AddError("name", "该名称已经有了")
handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{"form": form})
return
}
err = c.Insert(&PackageCategory{
Id_: bson.NewObjectId(),
Id: form.Value("id"),
Name: form.Value("name"),
})
if err != nil {
panic(err)
}
http.Redirect(handler.ResponseWriter, handler.Request, "/admin/package_category/new", http.StatusFound)
}
handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{
"form": form,
"isNew": true,
})
}
// URL: /admin/package_category/{id}/edit
// 修改包分类
func adminEditPackageCategoryHandler(handler *Handler) {
id := mux.Vars(handler.Request)["id"]
c := handler.DB.C(PACKAGE_CATEGORIES)
var category PackageCategory
c.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&category)
form := wtforms.NewForm(
wtforms.NewTextField("id", "ID", category.Id, wtforms.Required{}),
wtforms.NewTextField("name", "名称", category.Name, wtforms.Required{}),
)
if handler.Request.Method == "POST" {
if !form.Validate(handler.Request) {
handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{"form": form})
return
}
c.Update(bson.M{"_id": bson.ObjectIdHex(id)}, bson.M{"$set": bson.M{
"id": form.Value("id"),
"name": form.Value("name"),
}})
http.Redirect(handler.ResponseWriter, handler.Request, "/admin/package_categories", http.StatusFound)
}
handler.renderTemplate("package_category/form.html", ADMIN, map[string]interface{}{
"form": form,
"isNew": false,
})
}