-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoform.go
388 lines (318 loc) · 8.98 KB
/
goform.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Package goform Generate html forms dynamically and super simple using Golang/Go.
package goform
import (
"bytes"
"html/template"
"log"
"os"
"path"
"sort"
"strings"
)
var (
logForm []ErrorItem
fieldTypes = map[string]string{
"label": "label",
"text": "text",
"textlabel": "textlabel",
"password": "password",
"select": "select",
"radio": "radio",
"textarea": "textarea",
"checkbox": "checkbox",
"file": "file",
"hidden": "hidden",
"button": "button",
"submit": "submit",
"row": "row",
}
)
// Form structure.
type Form struct {
Name string
ID string
Method string
Action string
MultipartFormData string
TemplateStyle string
TemplateSource string
FormTypes map[string]int
Elements map[string]Field
Classes []string
CSS map[string]string
FormText string
FormTemplates map[string]*template.Template
GroupClass []string
}
// Element structure.
type Element struct {
ID int
Name string
}
// Field structure.
type Field struct {
Position int
FieldType string
Name string
ID string
Classes []string
CSS map[string]string
Label string
LabelClass []string
Value string
Options []OptionItem
PlaceHolder string
HelpText string
Params map[string]string
Set string
GroupClass []string
}
// OptionItem structure.
type OptionItem struct {
Key string
Value string
}
type FieldIndex struct {
Index int
Field Field
}
type ErrorItem struct {
RelatedTo string
Message string
}
//=============================================================================
// Create configure a new Form structure
func Create(name string, method string, action string) *Form {
return &Form{
name,
name,
method,
action,
"disabled",
"bootstrap5",
"",
make(map[string]int),
make(map[string]Field),
[]string{},
make(map[string]string),
"",
make(map[string]*template.Template),
[]string{},
}
}
// SetMultipartFormData set style format, (html or bootstrap5: default option)
func (f *Form) SetMultipartFormData(status string) {
f.MultipartFormData = status
}
// SetTemplateStyle set style format, (html or bootstrap5: default option)
func (f *Form) SetTemplateStyle(style string) {
f.TemplateStyle = style
}
// SetOwnTemplateStyle set style format, target different templates folder
// In case if any one need to use a custom templates
func (f *Form) SetOwnTemplateStyle(style string) {
f.TemplateStyle = style
f.TemplateSource = "OWN"
}
// DefaultGroupClass set default group classes for all the elements
func (f *Form) DefaultGroupClass(width string) {
f.GroupClass = append(f.GroupClass, width)
}
// Render returns form generated in plain format
func (f *Form) Render() template.HTML {
var tmpl *template.Template
buf := new(bytes.Buffer)
cwd := ""
var err error
if f.TemplateSource == "OWN" {
cwd, _ = os.Getwd()
cwd += path.Join("/templates/", f.TemplateStyle, ".html")
tmpl, err = template.ParseFiles(cwd)
if err != nil {
panic(err)
}
} else {
tmpl = HTMLTemplate(f.TemplateStyle, "form")
}
tmpl.Execute(buf, f)
return template.HTML(buf.String())
}
// RenderElements returns form elements generated in plain format
func (f *Form) RenderElements() template.HTML {
elementsSort := f.SortElements()
var tmpl *template.Template
buf := new(bytes.Buffer)
cwd := ""
var err error
// Load ONCE all the necesary templates depending the input types
for keyTemplate := range f.FormTypes {
if f.TemplateSource == "OWN" {
cwd, _ = os.Getwd()
cwd += path.Join("templates", f.TemplateStyle, keyTemplate, ".html")
tmpl, err = template.ParseFiles(cwd)
if err != nil {
panic(err)
}
} else {
tmpl = HTMLTemplate(f.TemplateStyle, keyTemplate)
}
f.FormTemplates[keyTemplate] = tmpl
}
// Apply the template to each item of the form
for _, itemForm := range elementsSort {
// Apply the default classes if exists, only if the element have not own group classes
if len(itemForm.GroupClass) == 0 && len(f.GroupClass) > 0 {
itemForm.GroupClass = f.GroupClass
}
f.FormTemplates[itemForm.FieldType].Execute(buf, itemForm)
f.FormText += buf.String()
// Clear buffer
buf = new(bytes.Buffer)
}
return template.HTML(f.FormText)
}
// EmptyField create and return empty form field
func EmptyField() Field {
field := Field{}
field.Position = 0
field.FieldType = ""
field.Name = ""
field.ID = ""
field.Classes = []string{}
field.CSS = map[string]string{}
field.Label = ""
field.LabelClass = []string{}
field.Value = ""
field.Options = []OptionItem{}
field.PlaceHolder = ""
field.HelpText = ""
field.Params = map[string]string{}
field.GroupClass = []string{}
return field
}
// SortElements create and return empty form field
func (f *Form) SortElements() []Field {
elementsIdexed := []FieldIndex{}
formElementsSorted := []Field{}
// Convert the Map into Slice
for _, v := range f.Elements {
elementsIdexed = append(elementsIdexed, FieldIndex{v.Position, v})
}
// Slice sort
sort.Slice(elementsIdexed, func(i, j int) bool {
return elementsIdexed[i].Index < elementsIdexed[j].Index
})
// Remove the index
for _, sortField := range elementsIdexed {
formElementsSorted = append(formElementsSorted, sortField.Field)
}
return formElementsSorted
}
// NewElement insert new form element
func (f *Form) NewElement(fieldType string, fieldName string, fieldValue string) string {
// fieldName remove spaces and convert un lowercase
fieldName = strings.ToLower(fieldName)
fieldName = strings.Replace(fieldName, " ", "", -1)
_, typeOk := fieldTypes[fieldType]
// If the key exists
if typeOk {
field := EmptyField()
field.Position = len(f.Elements) + 1
field.FieldType = fieldType
field.Name = fieldName
field.ID = fieldName
field.Value = fieldValue
// Apped/Or Increase the input-type counter of FormTypes map
// This map will is used in the RenderElements function
f.FormTypes[fieldType]++
_, fieldOk := f.Elements[fieldName]
if !fieldOk {
f.Elements[fieldName] = field
} else {
logForm = append(logForm, ErrorItem{RelatedTo: fieldName, Message: "Field Already Exists"})
}
} else {
logForm = append(logForm, ErrorItem{RelatedTo: fieldType, Message: "Type Do Not Exists"})
}
return fieldName
}
// NewRow insert a new row shortcut.
func (f *Form) NewRow(rowName string) {
f.NewElement("row", rowName, "")
}
// NewButton insert a new button shortcut.
func (f *Form) NewButton(buttonName string) {
f.NewElement("button", buttonName, "")
}
// SetID set/change the ID to the field.
func (f *Form) SetID(fieldName string, id string) {
// fieldID remove spaces and convert un lowercase
id = strings.ToLower(id)
id = strings.Replace(id, " ", "", -1)
field := f.Elements[fieldName]
field.ID = id
f.Elements[fieldName] = field
}
// SetLabel set/change the text label to the field.
func (f *Form) SetLabel(fieldName string, label string) {
field := f.Elements[fieldName]
field.Label = label
f.Elements[fieldName] = field
}
// AddClass adds a class to the input.
func (f *Form) AddClass(fieldName string, class string) {
field := f.Elements[fieldName]
field.Classes = append(field.Classes, class)
f.Elements[fieldName] = field
}
// AddCSS add a CSS value (in the form of option-value - e.g.: color - red).
func (f *Form) AddCSS(fieldName string, key, value string) {
f.Elements[fieldName].CSS[key] = value
}
// AddLabelClass adds a class to the label of the input.
func (f *Form) AddLabelClass(fieldName string, class string) {
field := f.Elements[fieldName]
field.LabelClass = append(field.LabelClass, class)
f.Elements[fieldName] = field
}
// SetOptions set/change the Options of the dropdown.
func (f *Form) SetOptions(fieldName string, options []OptionItem) {
field := f.Elements[fieldName]
field.Options = options
f.Elements[fieldName] = field
}
// SetPlaceHolder set the placeholder text to the input.
func (f *Form) SetPlaceHolder(fieldName string, placeholder string) {
field := f.Elements[fieldName]
field.PlaceHolder = placeholder
f.Elements[fieldName] = field
}
// SetHelpText set the help-text to the input.
func (f *Form) SetHelpText(fieldName string, helptext string) {
field := f.Elements[fieldName]
field.HelpText = helptext
f.Elements[fieldName] = field
}
// AddParams add a Param value (in the form of option-value - e.g.: maxlength - 15).
func (f *Form) AddParams(fieldName string, key, value string) {
f.Elements[fieldName].Params[key] = value
}
// AddGroupClass adds a class to the group input.
func (f *Form) AddGroupClass(fieldName string, class string) {
field := f.Elements[fieldName]
field.GroupClass = append(field.GroupClass, class)
f.Elements[fieldName] = field
}
// LogOutput display the Log
func LogOutput(format string) string {
text := ""
for _, logField := range logForm {
switch format {
case "return":
text += logField.RelatedTo + " : " + logField.Message + "\n\r"
default:
log.Println(logField.RelatedTo, logField.Message)
}
}
return text
}