forked from bluele/gforms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
booleanfield.go
84 lines (75 loc) · 1.59 KB
/
booleanfield.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
package gforms
import (
"bytes"
"reflect"
)
// It maps value to FormInstance.CleanedData as type `bool`.
type BooleanField struct {
BaseField
}
// Create a new BooleanField instance.
func (f *BooleanField) New() FieldInterface {
fi := new(BooleanFieldInstance)
fi.Model = f
fi.V = nilV("")
return fi
}
// Instance for BooleanField.
type BooleanFieldInstance struct {
FieldInstance
}
type booleanContext struct {
Field FieldInterface
Checked bool
}
// Create a new BooleanField with validators and widgets.
func NewBooleanField(name string, vs Validators, ws ...Widget) *BooleanField {
f := new(BooleanField)
f.name = name
f.validators = vs
if len(ws) > 0 {
f.widget = ws[0]
}
return f
}
// Get a value from request data, and clean it as type `bool`.
func (f *BooleanFieldInstance) Clean(data Data) error {
m, hasField := data[f.GetName()]
if hasField {
f.V = m
v := false
if m.Kind == reflect.String {
vs := m.rawValueAsString()
if vs != nil {
v = true
}
} else if m.Kind == reflect.Bool {
v = m.rawValueAsBool()
}
m.Value = v
m.Kind = reflect.Bool
m.IsNil = false
return nil
}
nv := newV("", false, reflect.Bool)
nv.Value = false
nv.IsNil = false
f.V = nv
return nil
}
func (f *BooleanFieldInstance) html() string {
var buffer bytes.Buffer
cx := new(booleanContext)
cx.Field = f
checked, _ := f.V.Value.(bool)
cx.Checked = checked
err := Template.ExecuteTemplate(&buffer, "BooleanTypeField", cx)
if err != nil {
panic(err)
}
return buffer.String()
}
// Get as HTML format.
func (f *BooleanFieldInstance) Html() string {
return fieldToHtml(f)
}