forked from bluele/gforms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
datetimefield.go
79 lines (68 loc) · 1.61 KB
/
datetimefield.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
package gforms
import (
"errors"
"reflect"
"time"
)
var DefaultDateFormat string = "2006-01-02"
var DefaultDateTimeFormat string = "2006-01-02 15:04:05"
// It maps value to FormInstance.CleanedData as type `time.Time`.
type DateTimeField struct {
BaseField
Format string
ErrorMessage string
}
// Create a new DateField instance.
func (f *DateTimeField) New() FieldInterface {
fi := new(DateTimeFieldInstance)
fi.Format = f.Format
if f.ErrorMessage == "" {
fi.ErrorMessage = "This field should be specified as date format."
} else {
fi.ErrorMessage = f.ErrorMessage
}
fi.Model = f
fi.V = nilV("")
return fi
}
// Instance for DateTimeField
type DateTimeFieldInstance struct {
FieldInstance
Format string
ErrorMessage string
}
// Create a new DateTimeField with validators and widgets.
func NewDateTimeField(name string, format string, vs Validators, ws ...Widget) *DateTimeField {
f := new(DateTimeField)
f.name = name
f.validators = vs
f.Format = format
if len(ws) > 0 {
f.widget = ws[0]
}
return f
}
// Get a value from request data, and clean it as type string
func (f *DateTimeFieldInstance) Clean(data Data) error {
m, hasField := data[f.Model.GetName()]
if hasField {
f.V = m
v := m.rawValueAsString()
m.Kind = reflect.Struct
if v != nil {
t, err := time.Parse(f.Format, *v)
if err != nil {
return errors.New(f.ErrorMessage)
}
m.Value = t
m.IsNil = false
}
}
return nil
}
func (f *DateTimeFieldInstance) html() string {
return renderTemplate("TextTypeField", newTemplateContext(f))
}
func (f *DateTimeFieldInstance) Html() string {
return fieldToHtml(f)
}