Эх сурвалжийг харах

Add label and html class fields in FormField.

Bozhin Zafirov 2 жил өмнө
parent
commit
09944b89d7
3 өөрчлөгдсөн 44 нэмэгдсэн , 9 устгасан
  1. 22 7
      constructors.go
  2. 20 0
      forms.go
  3. 2 2
      validate.go

+ 22 - 7
constructors.go

@@ -1,14 +1,29 @@
 package form
 
-/* Generate new CharField field with type text */
-func NewCharField(Name string, Value *string, Validators *ValidatorsList) FormField {
-	if Value == nil {
-		return FormField{Name, "", nil, Validators}
+///* Generate new CharField field with type text */
+//func NewCharField(Name string, Label *string, Value *string, Class *string, Validators *ValidatorsList) FormField {
+//	strFromPtr := func(str *string) (s string) {
+//		if str != nil {
+//			s = *str
+//		}
+//		return
+//	}
+//	return FormField{Name, strFromPtr(Label), strFromPtr(Value), strFromPtr(Class), nil, Validators}
+//}
+
+func strFromPtr(str *string) (s string) {
+	if str != nil {
+		s = *str
 	}
-	return FormField{Name, *Value, nil, Validators}
+	return
+}
+
+/* Generate new CharField field with type text */
+func NewCharField(Name string, Value *string) *FormField {
+	return &FormField{Name, "", strFromPtr(Value), "", nil, nil}
 }
 
 /* Generate new CharField field with type password */
-func NewPasswordField(Name string, Validators *ValidatorsList) FormField {
-	return FormField{Name, "", nil, Validators}
+func NewPasswordField(Name string) *FormField {
+	return NewCharField(Name, nil)
 }

+ 20 - 0
forms.go

@@ -14,11 +14,31 @@ type ValidatorsList []ValidatorFunc
 /* A general purpose form  field struct */
 type FormField struct {
 	Name       string
+	Label      string
 	Value      string
+	Class      string
 	Error      error
 	Validators *ValidatorsList
 }
 
+/* SetValidators configures validators list in form field */
+func (f FormField) SetValidators(validators *ValidatorsList) FormField {
+	f.Validators = validators
+	return f
+}
+
+/* SetLabel configures form label */
+func (f FormField) SetLabel(label string) FormField {
+	f.Label = label
+	return f
+}
+
+/* SetClass configures class name in form field */
+func (f FormField) SetClass(class string) FormField {
+	f.Class = class
+	return f
+}
+
 /* GetString returns FormField.Value as string */
 func (f FormField) GetString() string {
 	return f.Value

+ 2 - 2
validate.go

@@ -37,7 +37,7 @@ func ValidateForm(r *http.Request, p interface{}) error {
 			}
 			/* set form data to field
 			   equivalent of form.Value = HttpFormValue[0] */
-			fieldn.Field(1).Set(reflect.ValueOf(HttpFormValue[0]))
+			fieldn.Field(2).Set(reflect.ValueOf(HttpFormValue[0]))
 		}
 	}
 
@@ -50,7 +50,7 @@ func ValidateForm(r *http.Request, p interface{}) error {
 		}
 		for _, validator := range *field.Validators {
 			if err := validator(field, r.Context()); err != nil {
-				fieldn.Field(2).Set(reflect.ValueOf(err))
+				fieldn.Field(4).Set(reflect.ValueOf(err))
 				FormError = err
 				break
 			}