-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform_handler.go
94 lines (71 loc) · 1.99 KB
/
form_handler.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
package dhtmlform
import (
"net/http"
"github.com/mitoteam/dhtml"
)
type FormHandler struct {
RenderF func(formBody *dhtml.HtmlPiece, fd *FormData)
ValidateF func(fd *FormData)
SubmitF func(fd *FormData)
}
const hiddenBuildIdFieldName = "dhtmlform_build_id"
func (fh *FormHandler) Render(fc *FormContext) *dhtml.HtmlPiece {
rootTag := dhtml.Div().Class("dhtml-form")
var formBody dhtml.HtmlPiece
var fd = fc.getFormDataFromPOST()
if fd != nil { //found in POST values and data store
fd.redirectUrl = ""
fd.rebuild = false
//basic internal validations (like required values)
fd.ClearErrors()
fd.validateFormControls()
//rootTag.Append(dhtml.Dbg("%+v", fd))
// custom form handler validations
if fh.ValidateF != nil {
fh.ValidateF(fd)
}
// render errors if any
if fd.HasError() {
rootTag.Append(settings.FormErrorsRenderF(&fd.errors))
fd.rebuild = true //and display form again
}
// no rebuild requested, do submit
if !fd.rebuild {
if fh.SubmitF != nil {
fh.SubmitF(fd)
}
}
//rebuilt flag can be set in SubmitF() so check it again
if !fd.rebuild {
formDataStore.Remove(fd.build_id)
//check redirect (first from FormData, then from FormContext)
var redirectUrl = fd.redirectUrl
if redirectUrl == "" {
redirectUrl = fc.redirectUrl
}
if redirectUrl != "" {
http.Redirect(fc.w, fc.r, redirectUrl, http.StatusSeeOther)
return dhtml.NewHtmlPiece() //empty piece
}
//we are not rebuilding and not redirecting = new form should be built from scratch
fd = nil
}
}
if fd == nil {
fd = NewFormData()
fd.args.CopyFrom(&fc.args)
fd.params.CopyFrom(&fc.params)
}
//<form> tag
form := dhtml.NewForm().Method("post").
Append(NewHidden(hiddenBuildIdFieldName).Default(fd.build_id))
if fh.RenderF != nil {
fh.RenderF(&formBody, fd)
formBody.WalkR(fd.processControlDataWalkerF)
}
//save to store for rebuilds
formDataStore.Set(fd)
form.Append(formBody)
rootTag.Append(form)
return dhtml.Piece(rootTag)
}