This repository has been archived by the owner on Feb 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
checkboxwidget.go
107 lines (92 loc) · 2.02 KB
/
checkboxwidget.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
package gforms
import (
"bytes"
)
type checkboxMultipleWidget struct {
Attrs map[string]string
Maker CheckboxOptionsMaker
Widget
}
type checkboxOptionValue struct {
Label string
Value string
Checked bool
Disabled bool
}
type checkboxOptionValues []*checkboxOptionValue
type CheckboxContext struct {
Field FieldInterface
Attrs map[string]string
Options checkboxOptionValues
}
type CheckboxOptionsMaker func() CheckboxOptions
type CheckboxOptions interface {
Label(int) string
Value(int) string
Checked(int) bool
Disabled(int) bool
Len() int
}
type StringCheckboxOptions [][]string
func (opt StringCheckboxOptions) Label(i int) string {
return opt[i][0]
}
func (opt StringCheckboxOptions) Value(i int) string {
return opt[i][1]
}
func (opt StringCheckboxOptions) Checked(i int) bool {
checked := opt[i][2]
if checked == "true" {
return true
} else {
return false
}
}
func (opt StringCheckboxOptions) Disabled(i int) bool {
disabled := opt[i][3]
if disabled == "true" {
return true
} else {
return false
}
}
func (opt StringCheckboxOptions) Len() int {
return len(opt)
}
func (wg *checkboxMultipleWidget) html(f FieldInterface) string {
var buffer bytes.Buffer
ctx := new(CheckboxContext)
opts := wg.Maker()
for i := 0; i < opts.Len(); i++ {
ctx.Options = append(
ctx.Options,
&checkboxOptionValue{
Label: opts.Label(i),
Value: opts.Value(i),
Checked: opts.Checked(i),
Disabled: opts.Disabled(i),
})
}
ctx.Field = f
ctx.Attrs = wg.Attrs
err := Template.ExecuteTemplate(&buffer, "CheckboxMultipleWidget", ctx)
if err != nil {
panic(err)
}
return buffer.String()
}
// Generate checkbox input field: <input type="checkbox" ...>
func CheckboxMultipleWidget(attrs map[string]string, mk CheckboxOptionsMaker) *checkboxMultipleWidget {
wg := new(checkboxMultipleWidget)
if attrs == nil {
attrs = map[string]string{}
}
if isNilValue(mk) {
mk = func() CheckboxOptions {
return StringCheckboxOptions([][]string{})
}
}
wg.Maker = mk
wg.Attrs = attrs
return wg
}