diff --git a/form.go b/form.go new file mode 100644 index 0000000..a32e0a7 --- /dev/null +++ b/form.go @@ -0,0 +1,62 @@ +package goutil + +import ( + "encoding/json" + "strings" +) + +const ( + FormTypeInput = "input" //文本输入框 + FormTypeText = "text" //多行文本 + FormTypeRadio = "radio" //单选框 + FormTypeCheckbox = "checkbox" //多选框 + FormTypeSwitch = "switch" //开关 + FormTypeJson = "json" //JSON输入框 + FormTypeDatetime = "datetime" //时间选择框 + FormTypeDate = "date" //日期选择框 + FormTypeMonth = "month" //阅读选择框 +) + +type FormOption struct { + Name string `json:"name,omitempty"` //选项名称 + Value string `json:"value,omitempty"` //选项值 +} + +type Form struct { + Type string `json:"type,omitempty" ` //表单类型 + Name string `json:"name,omitempty"` //表单名称 + Key string `json:"key,omitempty"` //表单KEY + Value any `json:"value,omitempty"` //表单值 + Default any `json:"default,omitempty"` //默认值 + Disable bool `json:"disable,omitempty"` //是否禁用 + Tips string `json:"tips,omitempty"` //表单提示 + Option []*FormOption `json:"option,omitempty"` //表单选项,radio和checkbox需要 +} + +func NewForms(tplConfig, saveConfig string) ([]*Form, error) { + var forms []*Form + err := json.Unmarshal([]byte(tplConfig), &forms) + if err != nil { + return nil, err + } + + var cfg map[string]interface{} + if strings.TrimSpace(saveConfig) != "" { + err = json.Unmarshal([]byte(saveConfig), &cfg) + if err != nil { + return nil, err + } + } + if cfg == nil { + cfg = make(map[string]interface{}) + } + + for _, form := range forms { + if _, ok := cfg[form.Key]; ok { + form.Value = cfg[form.Key] + } else { + form.Value = form.Default + } + } + return forms, err +}