forked from kirves/go-form-it
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.go
221 lines (210 loc) · 6.17 KB
/
forms.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// This package provides form creation and rendering functionalities, as well as FieldSet definition.
// Two kind of forms can be created: base forms and Bootstrap3 compatible forms; even though the latters are automatically provided
// the required classes to make them render correctly in a Bootstrap environment, every form can be given custom parameters such as
// classes, id, generic parameters (in key-value form) and stylesheet options.
package forms
import (
"html/template"
"path"
"reflect"
"strings"
"github.com/bkrn/go-form-it/common"
"github.com/bkrn/go-form-it/fields"
)
// Form methods: POST or GET.
const (
POST = "POST"
GET = "GET"
)
// Form structure.
type Form struct {
Fields []FormElement
fieldMap map[string]int
containerMap map[string]string
style string
template *template.Template
class []string
id string
params map[string]string
css map[string]string
method string
action template.HTML
}
func getTemplate(nm string) *template.Template {
return template.New(path.Base(nm)).Funcs(
template.FuncMap{
"even": func(ix int, fes []FormElement) bool {
var cnt int
for fix, fe := range fes {
if fix > ix {
break
}
fi, is := fe.(*fields.Field)
if is && fi.Type() != "hidden" {
cnt++
}
}
return cnt%2 != 0
},
"lastIsOdd": func(ix int, fes []FormElement) bool {
var cnt int
for _, fe := range fes {
fi, is := fe.(*fields.Field)
if is && fi.Type() != "hidden" {
cnt++
}
}
return (len(fes)-ix) == 1 && cnt%2 == 0
},
"elemType": func(fe FormElement) string {
if fi, is := fe.(*fields.Field); is {
return fi.Type()
}
return ""
},
},
)
}
// BaseForm creates an empty form with no styling.
func BaseForm(method, action string) *Form {
nm := formcommon.CreateUrl("templates/baseform.html")
tmpl, err := getTemplate(nm).ParseFiles(nm)
if err != nil {
panic(err)
}
return &Form{
make([]FormElement, 0),
make(map[string]int),
make(map[string]string),
formcommon.BASE,
tmpl,
[]string{},
"",
map[string]string{},
map[string]string{},
method,
template.HTML(action),
}
}
// BootstrapForm creates an empty form compliant with Bootstrap3 CSS, both in structure and classes.
func BootstrapForm(method, action string) *Form {
nm := formcommon.CreateUrl("templates/baseform.html")
tmpl, err := getTemplate(nm).ParseFiles(nm)
if err != nil {
panic(err)
}
return &Form{
make([]FormElement, 0),
make(map[string]int),
make(map[string]string),
formcommon.BOOTSTRAP,
tmpl,
[]string{},
"",
map[string]string{},
map[string]string{},
method,
template.HTML(action),
}
}
// BaseFormFromModel returns a base form inferring fields, data types and contents from the provided instance.
// A Submit button is automatically added as a last field; the form is editable and fields can be added, modified or removed as needed.
// Tags can be used to drive automatic creation: change default widgets for each field, skip fields or provide additional parameters.
// Basic field -> widget mapping is as follows: string -> textField, bool -> checkbox, time.Time -> datetimeField, int -> numberField;
// nested structs are also converted and added to the form.
func BaseFormFromModel(m interface{}, method, action string) *Form {
form := BaseForm(method, action)
for _, v := range unWindStructure(m, "") {
form.Elements(v)
}
form.Elements(fields.SubmitButton("submit", "Submit"))
return form
}
// Same as BaseFormFromModel but returns a Bootstrap3 compatible form.
func BootstrapFormFromModel(m interface{}, method, action string) *Form {
form := BootstrapForm(method, action)
for _, v := range unWindStructure(m, "") {
form.Elements(v)
}
form.Elements(fields.SubmitButton("submit", "Submit"))
return form
}
func unWindStructure(m interface{}, baseName string) []fields.FieldInterface {
t := reflect.TypeOf(m)
v := reflect.ValueOf(m)
fieldList := make([]fields.FieldInterface, 0)
for i := 0; i < t.NumField(); i++ {
optionsArr := strings.Split(t.Field(i).Tag.Get("form_options"), ",")
options := make(map[string]struct{})
for _, opt := range optionsArr {
if opt != "" {
options[opt] = struct{}{}
}
}
if _, ok := options["skip"]; !ok {
widget := t.Field(i).Tag.Get("form_widget")
var f fields.FieldInterface
var fName string
if baseName == "" {
fName = t.Field(i).Name
} else {
fName = strings.Join([]string{baseName, t.Field(i).Name}, ".")
}
switch widget {
case "hidden":
f = fields.HiddenFieldFromInstance(m, i, fName)
case "text":
f = fields.TextFieldFromInstance(m, i, fName)
case "textarea":
f = fields.TextAreaFieldFromInstance(m, i, fName)
case "password":
f = fields.PasswordFieldFromInstance(m, i, fName)
case "select":
f = fields.SelectFieldFromInstance(m, i, fName, options)
case "date":
f = fields.DateFieldFromInstance(m, i, fName)
case "datetime":
f = fields.DatetimeFieldFromInstance(m, i, fName)
case "time":
f = fields.TimeFieldFromInstance(m, i, fName)
case "number":
f = fields.NumberFieldFromInstance(m, i, fName)
case "range":
f = fields.RangeFieldFromInstance(m, i, fName)
case "radio":
f = fields.RadioFieldFromInstance(m, i, fName)
case "static":
f = fields.StaticFieldFromInstance(m, i, fName)
default:
switch t.Field(i).Type.Kind().String() {
case "string":
f = fields.TextFieldFromInstance(m, i, fName)
case "bool":
f = fields.CheckboxFromInstance(m, i, fName, options)
case "time.Time":
f = fields.DatetimeFieldFromInstance(m, i, fName)
case "int":
f = fields.NumberFieldFromInstance(m, i, fName)
case "float":
f = fields.NumberFieldFromInstance(m, i, fName)
case "struct":
fieldList = append(fieldList, unWindStructure(v.Field(i).Interface(), fName)...)
f = nil
default:
f = fields.TextFieldFromInstance(m, i, fName)
}
}
if f != nil {
label := t.Field(i).Tag.Get("form_label")
if label == "none" {
} else if label != "" {
f.SetLabel(label)
} else {
f.SetLabel(strings.Title(t.Field(i).Name))
}
fieldList = append(fieldList, f)
}
}
}
return fieldList
}