forms

package module
v0.0.0-...-886ce9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2022 License: MIT Imports: 21 Imported by: 1

README

forms

Documentation

Overview

This package provides all the input fields logic and customization methods.

This package provides form creation and rendering functionalities, as well as FieldSet definition. Two kind of forms can be created: base forms and Bootstrap3 compatible forms; even though the latters are automatically provided the required classes to make them render correctly in a Bootstrap environment, every form can be given custom parameters such as classes, id, generic parameters (in key-value form) and stylesheet options.

This package contains the base logic for the creation and rendering of field widgets. Base widgets are defined for most input fields, both in classic and Bootstrap3 style; custom widgets can be defined and associated to a field, provided that they implement the WidgetInterface interface.

Index

Constants

View Source
const (
	DATETIME_FORMAT = "2006-01-02T15:05"
	DATE_FORMAT     = "2006-01-02"
	TIME_FORMAT     = "15:05"
)

Datetime format string to convert from time.Time objects to HTML fields and viceversa.

View Source
const (
	POST = "POST"
	GET  = "GET"
)

Form methods: POST or GET.

View Source
const (
	BUTTON             = "button"
	CHECKBOX           = "checkbox"
	COLOR              = "color" // Not yet implemented
	DATE               = "date"
	DATETIME           = "datetime"
	DATETIME_LOCAL     = "datetime-local"
	EMAIL              = "email"      // Not yet implemented
	FILE               = "file"       // Not yet implemented
	SINGLEFILE         = "singlefile" // Not yet implemented
	HIDDEN             = "hidden"
	IMAGE              = "image" // Not yet implemented
	MONTH              = "month" // Not yet implemented
	NUMBER             = "number"
	PASSWORD           = "password"
	RADIO              = "radio"
	RANGE              = "range"
	RESET              = "reset"
	SEARCH             = "search" // Not yet implemented
	SUBMIT             = "submit"
	TEL                = "tel" // Not yet implemented
	TEXT               = "text"
	TIME               = "time"
	URL                = "url"  // Not yet implemented
	WEEK               = "week" // Not yet implemented
	TEXTAREA           = "textarea"
	SELECT             = "select"
	MULI_SOURCE_SELECT = "mult_source_select"
	STATIC             = "static"
	CRON               = "cron"
	MAP                = "map"
)

Input field types

View Source
const (
	BASE      = "base"
	BOOTSTRAP = "bootstrap3"
)

Available form styles

Variables

View Source
var (
	FieldFuncs = template.FuncMap{
		"f_setName": func(name string, field FieldInterface) FieldInterface {
			field.SetName(name)
			return field
		},
		"f_setLabel": func(label string, field FieldInterface) FieldInterface {
			field.SetLabel(label)
			return field
		},
		"f_setOptText": func(label string, field FieldInterface) FieldInterface {
			field.SetOptText(label)
			return field
		},
		"f_addClass": func(class string, field FieldInterface) FieldInterface {
			field.AddClass(class)
			return field
		},
		"f_removeClass": func(class string, field FieldInterface) FieldInterface {
			field.RemoveClass(class)
			return field
		},
		"f_addLabelClass": func(class string, field FieldInterface) FieldInterface {
			field.AddLabelClass(class)
			return field
		},
		"f_removeLabelClass": func(class string, field FieldInterface) FieldInterface {
			field.RemoveLabelClass(class)
			return field
		},
		"f_addTag": func(class string, field FieldInterface) FieldInterface {
			field.AddTag(class)
			return field
		},
		"f_removeTag": func(class string, field FieldInterface) FieldInterface {
			field.RemoveTag(class)
			return field
		},
		"f_setId": func(id string, field FieldInterface) FieldInterface {
			field.SetID(id)
			return field
		},
		"f_addParams": func(key, value string, field FieldInterface) FieldInterface {
			field.SetParam(key, value)
			return field
		},
		"f_removeParams": func(key string, field FieldInterface) FieldInterface {
			field.DeleteParam(key)
			return field
		},
		"f_addCss": func(key, value string, field FieldInterface) FieldInterface {
			field.AddCSS(key, value)
			return field
		},
		"f_removeCss": func(key string, field FieldInterface) FieldInterface {
			field.RemoveCSS(key)
			return field
		},
		"f_setTheme": func(style string, field FieldInterface) FieldInterface {
			field.SetTheme(style)
			return field
		},
		"f_setValue": func(value interface{}, field FieldInterface) FieldInterface {
			field.SetValue(value)
			return field
		},
		"f_setText": func(text string, field FieldInterface) FieldInterface {
			field.SetText(text)
			return field
		},
		"f_disabled": func(field FieldInterface) FieldInterface {
			field.Disabled()
			return field
		},
		"f_enabled": func(field FieldInterface) FieldInterface {
			field.Enabled()
			return field
		},
		"f_setReadOnly": func(isReadOnly bool, field FieldInterface) FieldInterface {
			if isReadOnly {
				field.SetParam("readonly", "readonly")
			} else {
				field.DeleteParam("readonly")
			}
			return field
		},
		"f_readOnly": func(field FieldInterface) FieldInterface {
			field.SetParam("readonly", "readonly")
			return field
		},
		"f_helpText": func(text string, field FieldInterface) FieldInterface {
			field.SetHelptext(text)
			return field
		},
		"f_addError": func(err string, field FieldInterface) FieldInterface {
			field.AddError(err)
			return field
		},
		"f_addData": func(key string, value interface{}, field FieldInterface) FieldInterface {
			field.AddData(key, value)
			return field
		},
		"f_nolabel": func(field FieldInterface) FieldInterface {
			field.AddData("nolabel", "true")
			return field
		},
		"f_multiple": func(field FieldInterface) FieldInterface {
			field.MultipleChoice()
			return field
		},
		"f_selected": func(options []string, field FieldInterface) FieldInterface {
			field.AddSelected(options...)
			return field
		},
		"f_containNull": func(field FieldInterface) FieldInterface {
			field.SetContainNull()
			return field
		},

		"f_addSource": func(name, label string, hasNew bool, choices interface{}, field FieldInterface) FieldInterface {
			return field.(*Field).AddSource(name, label, hasNew, choices)
		},

		"render": func(args ...interface{}) template.HTML {
			switch len(args) {
			case 0:
				panic("render 方法必须有一个 FieldInterface 参数")
			case 1:
				field, ok := args[0].(FieldInterface)
				if !ok {

					renderer, ok := args[0].(interface {
						Render() template.HTML
					})
					if ok {
						return renderer.Render()
					}

					rendererString, ok := args[0].(interface {
						Render() string
					})
					if ok {
						return template.HTML(rendererString.Render())
					}

					panic("render 方法的参数必须是 FieldInterface 类型")
				}
				return field.Render("")
			case 2:
				theme, ok := args[0].(string)
				if !ok {
					panic("render 方法的第一个参数必须是 string 类型")
				}

				field, ok := args[1].(FieldInterface)
				if !ok {
					renderer, ok := args[1].(interface {
						Render(string) template.HTML
					})
					if ok {
						return renderer.Render(theme)
					}

					rendererString, ok := args[1].(interface {
						Render(string) string
					})
					if ok {
						return template.HTML(rendererString.Render(theme))
					}

					panic("render 方法的第二个参数必须是 FieldInterface 类型")
				}
				return field.Render(theme)
			default:
				panic("render 方法的参数个数太多")
			}
		},
	}
)
View Source
var HierarchyChoicePtrType = reflect.TypeOf(&HierarchyChoice{})
View Source
var HierarchyChoiceType = reflect.TypeOf(HierarchyChoice{})
View Source
var InputChoicePtrType = reflect.TypeOf(&InputChoice{})
View Source
var InputChoiceType = reflect.TypeOf(InputChoice{})
View Source
var MapToString = func(v interface{}) string {
	if v == nil {
		return ""
	}
	m, ok := v.(map[string]interface{})
	if !ok {
		panic(fmt.Errorf("MapToString: value is not map - %T `%v`", v, v))
	}
	var buf bytes.Buffer
	buf.WriteString("# 一行为一条记录,以等号分隔键和值\r\n")
	buf.WriteString("# 以 # 开始的行及空行将忽略\r\n")
	for k, v := range m {
		buf.WriteString(k)
		buf.WriteString("=")
		buf.WriteString(fmt.Sprint(v))
		buf.WriteString("\r\n")
	}
	return buf.String()
}
View Source
var StrArrayPtrType = reflect.TypeOf([2]string{})

Functions

func CreateURL

func CreateURL(widget string) string

CreateURL creates the complete url of the desired widget template

func Init

func Init(devMode bool, root string, funcs template.FuncMap)

Types

type Field

type Field struct {
	// contains filtered or unexported fields
}

Field is a generic type containing all data associated to an input field.

func Button

func Button(ctx interface{}, name string, text string) *Field

Button creates a default generic button

func Checkbox

func Checkbox(ctx interface{}, name, label string) *Field

Checkbox creates a default checkbox field with the provided name. It also makes it checked by default based on the checked parameter.

func CronField

func CronField(ctx interface{}, name, label string) *Field

CronField creates a default text input field based on the provided name.

func DateField

func DateField(ctx interface{}, name, label string) *Field

DateField creates a default date input field with the given name.

func DatetimeField

func DatetimeField(ctx interface{}, name, label string) *Field

DatetimeField creates a default datetime input field with the given name.

func EmailField

func EmailField(ctx interface{}, name, label string) *Field

EmailField creates a default email input field based on the provided name.

func FieldWithType

func FieldWithType(ctx interface{}, name, t string) *Field

FieldWithType creates an empty field of the given type and identified by name.

func FieldWithTypeWithCtx

func FieldWithTypeWithCtx(ctx interface{}, name, label, typ string) *Field

FieldWithTypeWithCtx creates an field of the given type and identified by name.

func FileField

func FileField(ctx interface{}, name, label string) *Field

FileField creates a default file input field based on the provided name.

func HiddenField

func HiddenField(ctx interface{}, name string) *Field

HiddenField creates a default hidden input field based on the provided name.

func IPAddressField

func IPAddressField(ctx interface{}, name, label string) *Field

IPAddressField creates a default ip input field based on the provided name.

func MultSourceSelectField

func MultSourceSelectField(ctx interface{}, label string) *Field

MultSourceSelectField creates a default select input field with the provided name and map of choices. Choices for SelectField are grouped by name (if <optgroup> is needed); "" group is the default one and does not trigger a <optgroup></optgroup> rendering.

func NumberField

func NumberField(ctx interface{}, name, label string) *Field

NumberField craetes a default number field with the provided name.

func PasswordField

func PasswordField(ctx interface{}, name, label string) *Field

PasswordField creates a default password text input field based on the provided name.

func RadioField

func RadioField(ctx interface{}, name, label string, choices interface{}) *Field

RadioField creates a default radio button input field with the provided name and list of choices.

func RangeField

func RangeField(ctx interface{}, name, label string, min, max, step int64) *Field

RangeField creates a default range field with the provided name. Min, max and step parameters define the expected behavior of the HTML field.

func ResetButton

func ResetButton(ctx interface{}, name string, text string) *Field

ResetButton creates a default reset button with the provided name and text.

func SelectField

func SelectField(ctx interface{}, name, label string, choices interface{}) *Field

SelectField creates a default select input field with the provided name and map of choices. Choices for SelectField are grouped by name (if <optgroup> is needed); "" group is the default one and does not trigger a <optgroup></optgroup> rendering.

func SingleFileField

func SingleFileField(ctx interface{}, name, label string) *Field

FileField creates a default file input field based on the provided name.

func StaticField

func StaticField(name, content string) *Field

StaticField returns a static field with the provided name and content

func SubmitButton

func SubmitButton(ctx interface{}, name string, text string) *Field

SubmitButton creates a default button with the provided name and text.

func TextAreaField

func TextAreaField(ctx interface{}, name, label string, rows, cols int) *Field

TextAreaField creates a default textarea input field based on the provided name and dimensions.

func TextField

func TextField(ctx interface{}, name, label string) *Field

TextField creates a default text input field based on the provided name.

func TimeField

func TimeField(ctx interface{}, name, label string) *Field

TimeField creates a default time input field with the given name.

func (*Field) AddCSS

func (f *Field) AddCSS(key, value string) FieldInterface

AddCSS adds a custom CSS style the field.

func (*Field) AddClass

func (f *Field) AddClass(class string) FieldInterface

AddClass adds a class to the field.

func (*Field) AddData

func (f *Field) AddData(key string, value interface{}) FieldInterface

AddData adds a k/v to the additional data.

func (*Field) AddError

func (f *Field) AddError(err string) FieldInterface

AddError adds an error string to the field. It's valid only for Bootstrap forms.

func (*Field) AddLabelClass

func (f *Field) AddLabelClass(class string) FieldInterface

AddLabelClass allows to define custom classes for the label.

func (*Field) AddSelected

func (f *Field) AddSelected(opt ...string) FieldInterface

AddSelected If the field is configured as "multiple", AddSelected adds a selected value to the field (valid for SelectFields only). It has no effect if type is not SELECT.

func (*Field) AddSource

func (f *Field) AddSource(name, label string, hasNew bool, choices interface{}) *Field

func (*Field) AddTag

func (f *Field) AddTag(tag string) FieldInterface

AddTag adds a no-value parameter (e.g.: checked, disabled) to the field.

func (*Field) DeleteParam

func (f *Field) DeleteParam(key string) FieldInterface

DeleteParam removes a parameter identified by key from the field.

func (*Field) Disabled

func (f *Field) Disabled() FieldInterface

Disabled add the "disabled" tag to the field, making it unresponsive in some environments (e.g. Bootstrap).

func (*Field) Enabled

func (f *Field) Enabled() FieldInterface

Enabled removes the "disabled" tag from the field, making it responsive.

func (*Field) HasTag

func (f *Field) HasTag(tag string) bool

HasTag has a no-value parameter in the field.

func (*Field) IsMultipleChoice

func (f *Field) IsMultipleChoice() bool

IsMultipleChoice is a multiple choices.

func (*Field) MultipleChoice

func (f *Field) MultipleChoice() FieldInterface

MultipleChoice configures the SelectField to accept and display multiple choices. It has no effect if type is not SELECT.

func (*Field) Name

func (f *Field) Name() string

Name returns the name of the field.

func (*Field) RemoveCSS

func (f *Field) RemoveCSS(key string) FieldInterface

RemoveCSS removes CSS options identified by key from the field.

func (*Field) RemoveClass

func (f *Field) RemoveClass(class string) FieldInterface

RemoveClass removes a class from the field, if it was present.

func (*Field) RemoveLabelClass

func (f *Field) RemoveLabelClass(class string) FieldInterface

RemoveLabelClass removes the given class from the field label.

func (*Field) RemoveSelected

func (f *Field) RemoveSelected(opt string) FieldInterface

RemoveSelected If the field is configured as "multiple", AddSelected removes the selected value from the field (valid for SelectFields only). It has no effect if type is not SELECT.

func (*Field) RemoveTag

func (f *Field) RemoveTag(tag string) FieldInterface

RemoveTag removes a no-value parameter from the field.

func (*Field) Render

func (f *Field) Render(theme string) template.HTML

Render packs all data and executes widget render method.

func (*Field) SetContainNull

func (f *Field) SetContainNull() FieldInterface

func (*Field) SetHelptext

func (f *Field) SetHelptext(text string) FieldInterface

SetHelptext saves the field helptext.

func (*Field) SetID

func (f *Field) SetID(id string) FieldInterface

SetID associates the given id to the field, overwriting any previous id.

func (*Field) SetIntParam

func (f *Field) SetIntParam(key string, value int64) FieldInterface

SetIntParam adds a parameter (defined as key-value pair) in the field.

func (*Field) SetLabel

func (f *Field) SetLabel(label string) FieldInterface

SetLabel saves the label to be rendered along with the field.

func (*Field) SetName

func (f *Field) SetName(name string) FieldInterface

SetName set the name of the field.

func (*Field) SetOptText

func (f *Field) SetOptText(optText string) FieldInterface

SetLabel saves the label to be rendered along with the field.

func (*Field) SetParam

func (f *Field) SetParam(key, value string) FieldInterface

SetParam adds a parameter (defined as key-value pair) in the field.

func (*Field) SetRadioChoices

func (f *Field) SetRadioChoices(choices []InputChoice) FieldInterface

SetRadioChoices sets an array of InputChoice objects as the possible choices for a radio field. It has no effect if type is not RADIO.

func (*Field) SetSelectChoices

func (f *Field) SetSelectChoices(choices []HierarchyChoice) FieldInterface

SetSelectChoices takes as input a dictionary whose key-value entries are defined as follows: key is the group name (the empty string is the default group that is not explicitly rendered) and value is the list of choices belonging to that group. Grouping is only useful for Select fields, while groups are ignored in Radio fields. It has no effect if type is not SELECT.

func (*Field) SetText

func (f *Field) SetText(text string) FieldInterface

SetText saves the provided text as content of the field, usually a TextAreaField.

func (*Field) SetTheme

func (f *Field) SetTheme(style string) FieldInterface

SetTheme sets the style (e.g.: BASE, BOOTSTRAP) of the field, correctly populating the Widget field.

func (*Field) SetValue

func (f *Field) SetValue(value interface{}) FieldInterface

SetValue sets the value parameter for the field.

func (*Field) SingleChoice

func (f *Field) SingleChoice() FieldInterface

SingleChoice configures the Field to accept and display only one choice (valid for SelectFields only). It has no effect if type is not SELECT.

func (*Field) String

func (f *Field) String() string

type FieldInterface

type FieldInterface interface {
	SetName(name string) FieldInterface
	Name() string
	Render(string) template.HTML
	AddClass(class string) FieldInterface
	AddData(key string, value interface{}) FieldInterface
	RemoveClass(class string) FieldInterface
	AddTag(class string) FieldInterface
	RemoveTag(class string) FieldInterface
	SetID(id string) FieldInterface
	SetParam(key, value string) FieldInterface
	DeleteParam(key string) FieldInterface
	AddCSS(key, value string) FieldInterface
	RemoveCSS(key string) FieldInterface
	SetTheme(style string) FieldInterface
	SetLabel(label string) FieldInterface
	SetOptText(optText string) FieldInterface
	AddLabelClass(class string) FieldInterface
	RemoveLabelClass(class string) FieldInterface
	SetValue(value interface{}) FieldInterface
	Disabled() FieldInterface
	Enabled() FieldInterface
	SetHelptext(text string) FieldInterface
	AddError(err string) FieldInterface
	MultipleChoice() FieldInterface
	SingleChoice() FieldInterface
	AddSelected(opt ...string) FieldInterface
	RemoveSelected(opt string) FieldInterface
	SetSelectChoices(choices []HierarchyChoice) FieldInterface
	SetRadioChoices(choices []InputChoice) FieldInterface
	SetText(text string) FieldInterface
	SetContainNull() FieldInterface
}

FieldInterface defines the interface an object must implement to be used in a form. Every method returns a FieldInterface object to allow methods chaining.

type FieldSetType

type FieldSetType struct {
	// contains filtered or unexported fields
}

FieldSetType is a collection of fields grouped within a form.

func FieldSet

func FieldSet(name string, elems ...FieldInterface) *FieldSetType

FieldSet creates and returns a new FieldSetType with the given name and list of Every method for FieldSetType objects returns the object itself, so that call can be chained.

func (*FieldSetType) AddClass

func (f *FieldSetType) AddClass(class string) *FieldSetType

AddClass saves the provided class for the fieldset.

func (*FieldSetType) AddTag

func (f *FieldSetType) AddTag(tag string) *FieldSetType

AddTag adds a no-value parameter (e.g.: "disabled", "checked") to the fieldset.

func (*FieldSetType) Disable

func (f *FieldSetType) Disable() *FieldSetType

Disable adds tag "disabled" to the fieldset, making it unresponsive in some environment (e.g.: Bootstrap).

func (*FieldSetType) Enable

func (f *FieldSetType) Enable() *FieldSetType

Enable removes tag "disabled" from the fieldset, making it responsive.

func (*FieldSetType) Field

func (f *FieldSetType) Field(name string) FieldInterface

Field returns the field identified by name. It returns an empty field if it is missing.

func (*FieldSetType) Name

func (f *FieldSetType) Name() string

Name returns the name of the fieldset.

func (*FieldSetType) RemoveClass

func (f *FieldSetType) RemoveClass(class string) *FieldSetType

RemoveClass removes the provided class from the fieldset, if it was present. Nothing is done if it was not originally present.

func (*FieldSetType) RemoveTag

func (f *FieldSetType) RemoveTag(tag string) *FieldSetType

RemoveTag removes a tag from the fieldset, if it was present.

func (*FieldSetType) Render

func (f *FieldSetType) Render(theme string) template.HTML

Render translates a FieldSetType into HTML code and returns it as a template.HTML object.

type FieldValue

type FieldValue interface {
	Flash() string
	FlashArray() []string
	Value() interface{}
}

type Form

type Form struct {
	// contains filtered or unexported fields
}

Form structure.

func BaseForm

func BaseForm(method, action string) *Form

BaseForm creates an empty form with no styling.

func BootstrapForm

func BootstrapForm(method, action string) *Form

BootstrapForm creates an empty form compliant with Bootstrap3 CSS, both in structure and classes.

func (*Form) AddClass

func (f *Form) AddClass(class string) *Form

AddClass associates the provided class to the Form.

func (*Form) AddCss

func (f *Form) AddCss(key, value string) *Form

AddCss add a CSS value (in the form of option-value - e.g.: border - auto) to the form.

func (*Form) DeleteParam

func (f *Form) DeleteParam(key string) *Form

DeleteParm removes the parameter identified by key from form parameters list.

func (*Form) Elements

func (f *Form) Elements(elems ...Renderable) *Form

Elements adds the provided elements to the form.

func (*Form) Field

func (f *Form) Field(name string) FieldInterface

Field returns the field identified by name. It returns an empty field if it is missing.

func (*Form) FieldSet

func (f *Form) FieldSet(name string) *FieldSetType

Field returns the field identified by name. It returns an empty field if it is missing.

func (*Form) RemoveClass

func (f *Form) RemoveClass(class string) *Form

RemoveClass removes the given class (if present) from the Form.

func (*Form) RemoveCss

func (f *Form) RemoveCss(key string) *Form

RemoveCss removes CSS style from the form.

func (*Form) RemoveElement

func (f *Form) RemoveElement(name string) *Form

RemoveElement removes an element (identified by name) from the Form.

func (*Form) Render

func (f *Form) Render(theme string) template.HTML

Render executes the internal template and renders the form, returning the result as a template.HTML object embeddable in any other template.

func (*Form) SetId

func (f *Form) SetId(id string) *Form

SetId set the given id to the form.

func (*Form) SetParam

func (f *Form) SetParam(key, value string) *Form

SetParam adds the given key-value pair to form parameters list.

type HierarchyChoice

type HierarchyChoice = toolbox.HierarchyChoice

func AppendHierarchyChoices

func AppendHierarchyChoices(allList, parts []HierarchyChoice) []HierarchyChoice

type InputChoice

type InputChoice = toolbox.InputChoice

InputChoice - Value pair used to define an option for select and redio input fields.

func ToChoices

func ToChoices(name string, v interface{}) []InputChoice

type OptionSetReader

type OptionSetReader interface {
	Read() (nogroup bool, options interface{})
}

func ToOptionSetReader

func ToOptionSetReader(nogroup bool, options interface{}) OptionSetReader

type Renderable

type Renderable interface {
	Render(theme string) template.HTML
}

FormElement interface defines a form object (usually a Field or a FieldSet) that can be rendered as a template.HTML object.

type Widget

type Widget interface {
	Render(data interface{}) string
}

WidgetInterface defines the requirements for custom widgets.

func BaseWidget

func BaseWidget(style, inputType string) Widget

BaseWidget creates a Widget based on style and inpuType parameters, both defined in the common package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL