forms

package module
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2023 License: MIT Imports: 18 Imported by: 7

README

forms

GoDoc

Description

forms makes form creation and handling easy. It allows the creation of form without having to write HTML code or bother to make the code Bootstrap compatible. You can just create your form instance and add / populate / customize fields based on your needs. Or you can let forms do that for you starting from any object instance.

To integrate forms forms into your application simply pass the form object to the template and call its Render method. In your code:

tmpl.Execute(buf, map[string]interface{}{"form": form})

In your template:

{{ if .form }}{{ .form.Render }}{{ end }}

Installation

To install this package simply:

go get github.com/coscms/forms

Forms

There are two predefined themes for forms: base HTML forms and Bootstrap forms: they have different structures and predefined classes. Style aside, forms can be created from scratch or starting from a base instance.

From scratch

You can create a form instance by simply deciding its theme and providing its method and action:

form := NewWithConfig(&config.Config{
    Theme:"base", 
    Method:POST, 
    Action:"/action.html",
})

Now that you have a form instance you can customize it by adding classes, parameters, CSS values or id. Each method returns a pointer to the same form, so multiple calls can be chained:

form.SetID("TestForm").AddClass("form").AddCSS("border", "auto")

Obviously, elements can be added as well:

form.Elements(fields.TextField("text_field"))

Elements can be either FieldSets or Fields: the formers are simply collections of fields translated into a <fieldset></fieldset> element. Elements are added in order, and they are displayed in the exact same order. Note that single elements can be removed from a form referencing them by name:

form.RemoveElement("text_field")

Typical usage looks like this:

form := NewWithConfig(&config.Config{
    Theme:"base", 
    Method:POST, 
    Action:"/action.html",
}).Elements(
    fields.TextField("text_field").SetLabel("Username"),
    FieldSet("psw_fieldset",
        fields.PasswordField("psw1").AddClass("password_class").SetLabel("Password 1"),
        fields.PasswordField("psw2").AddClass("password_class").SetLabel("Password 2"),
        ),
    fields.SubmitButton("btn1", "Submit"),
    )

validation:

type User struct {
    Username     string    `valid:"Required;AlphaDash;MaxSize(30)"`
    Password1     string    `valid:"Required"`
    Password2    string    `valid:"Required"`
}
u := &User{}
form.SetModel(u) //Must set model
err := form.valid()
if err != nil { 
    // validation does not pass
}

Details about validation, please visit: https://github.com/webx-top/validation

A call to form.Render() returns the following form:

<form method="POST" action="/action.html">
    <label>Username</label>
    <input type="text" name="text_field">
    <fieldset>
        <label>Password 1</label>
        <input type="password" name="psw1" class="password_class ">
        <label>Password 2</label>
        <input type="password" name="psw2" class="password_class ">
    </fieldset>
    <button type="submit" name="btn1">Submit</button>
</form>

From model instance

Instead of manually creating a form, it can be automatically created from an existing model instance: the package will try to infer the field types based on the instance fields and fill them accordingly. Default type-to-field mapping is as follows:

  • string: TextField
  • bool: Checkbox
  • time.Time: DatetimeField
  • int: NumberField
  • struct: recursively parse

You can customize field behaviors by adding tags to instance fields. Without tags this code:

type User struct {
    Username     string
    Password1     string
    Password2    string
}
u := &User{}
form := NewFromModel(u, &config.Config{
    Theme:"bootstrap3", 
    Method:POST, 
    Action:"/action.html",
})

validation:

err := form.valid()
if err != nil { 
    // validation does not pass
}
form.Render()

would yield this HTML form:

<form method="POST" action="/action.html">
    <label>Username</label>
    <input type="text" name="Username">
    <label>Password1</label>
    <input type="text" name="Password1">
    <label>Password2</label>
    <input type="text" name="Password2">
    <button type="submit" name="submit">Submit</button>
</form>

A submit button is added by default.

Notice that the form is still editable and fields can be added, modified or removed like before.

When creating a form from a model instance, field names are created by appending the field name to the baseline; the baseline is empty for single level structs but is crafted when nested structs are found: in this case it becomes the field name followed by a dot. So for example, if the struct is:

type A struct {
    field1     int
    field2     int
}
type B struct {
    field0     int
    struct1    A
}

The final form will contain fields "field0", "struct1.field1" and "struct1.field2".

Tags

Struct tags can be used to slightly modify automatic form creation. In particular the following tags are parsed:

  • form_options: can contain the following keywords separated by Semicolon (;)

    • -: skip field, do not convert to HTML field
    • checked: for Checkbox fields, check by default
    • multiple: for select fields, allows multiple choices
  • form_widget: override custom widget with one of the following

    • text
    • hidden
    • textarea
    • password
    • select
    • datetime
    • date
    • time
    • number
    • range
    • radio
    • checkbox
    • static (simple text)
  • form_fieldset: define fieldset name

  • form_sort: sort number (asc, 0 ~ total-1)

  • form_choices: defines options for select and radio input fields

    • radio/checkbox example(format: id|value): 1|Option One|2|Option 2|3|Option 3
    • select example(format: group|id|value): G1|A|Option A|G1|B|Option B
      • "" group is the default one and does not trigger a <optgroup></optgroup> rendering.
  • form_max: max value (number, range, datetime, date and time fields)

  • form_min: min value (number, range, datetime, date and time fields)

  • form_step: step value (range field)

  • form_rows: number of rows (textarea field)

  • form_cols: number of columns (textarea field)

  • form_value: input field value (used if field is empty)

  • form_label: label for input field

The code would therefore be better like this:

type User struct {
    Username     string
    Password1     string     `form_widget:"password" form_label:"Password 1"`
    Password2    string     `form_widget:"password" form_label:"Password 2"`
    SkipThis    int     `form_options:"-"`
}
u := User{}
form := NewFromModel(u, &config.Config{
    Theme:"bootstrap3", 
    Method:POST, 
    Action:"/action.html",
})
form.Render()

which translates into:

<form method="POST" action="/action.html">
    <label>Username</label>
    <input type="text" name="Username">
    <label>Password 1</label>
    <input type="password" name="Password1">
    <label>Password 2</label>
    <input type="password" name="Password2">
    <button type="submit" name="submit">Submit</button>
</form>

Fields

Field objects in forms implement the fields.FieldInterface which exposes methods to edit classes, parameters, tags and CSS styles. See the documentation for details.

Most of the field widgets have already been created and integrate with Bootstrap. It is possible, however, to define custom widgets to render fields by simply assigning an object implementing the widgets.WidgetInterface to the Widget field.

Also, error messages can be added to fields via the AddError(err) method: in a Bootstrap environment they will be correctly rendered.

Text fields

This category includes text, password, textarea and hidden fields. They are all instantiated by providing the name, except the TextAreaField which also requires a dimension in terms of rows and columns.

f0 := fields.TextField("text")
f1 := fields.PasswordField("password")
f2 := fields.HiddenField("hidden")
f3 := fields.TextAreaField("textarea", 30, 50)

Option fields

This category includes checkbox, select and radio button fields. Checkbox field requires a name and a set of options to populate the field. The options are just a set of InputChoice (ID-Value pairs) objects:

opts := []fields.InputChoice{
    fields.InputChoice{ID:"A", Val:"Option A"},
    fields.InputChoice{ID:"B", Val:"Option B"},
}
f := fields.CheckboxField("checkbox", opts)
f.AddSelected("A", "B")

Radio buttons, instead, require a name and a set of options to populate the field. The options are just a set of InputChoice (ID-Value pairs) objects:

opts := []fields.InputChoice{
    fields.InputChoice{ID:"A", Val:"Option A"},
    fields.InputChoice{ID:"B", Val:"Option B"},
}
f := fields.RadioField("radio", opts)

Select fields, on the other hand, allow option grouping. This can be achieved by passing a map[string][]InputChoice in which keys are groups containing choices given as values; the default (empty) group is "", which is not translated into any <optgroup></optgroup> element.

opts := map[string][]fields.InputChoice{
    "": []fields.InputChoice{fields.InputChoice{"A", "Option A"}},
    "group1": []fields.InputChoice{
        fields.InputChoice{ID:"B", Val:"Option B"},
        fields.InputChoice{ID:"C", Val:"Option C"},
    }
}
f := fields.SelectField("select", opts)

Select fields can allow multiple choices. To enable this option simply call the MultipleChoice() method on the field and provide the selected choices via AddSelected(...string):

f.MultipleChoice()
f.AddSelected("A", "B")

Number fields

Number and range fields are included. Number field only require a name to be instantiated; minimum and maximum values can optionally be set by adding min and max parameters respectively.

f := fields.NumberField("number")
f.SetParam("min", "1")

Range fields, on the other hand, require both minimum and maximum values (plus the identifier). The optional "step" value is set via SetParam.

f := fields.RangeField("range", 1, 10)
f.SetParam("step", "2")

Datetime fields

Datetime, date and time input fields are defined in forms.

f0 := fields.DatetimeField("datetime")
f1 := fields.DateField("date")
f2 := fields.TimeField("time")

Values can be set via SetValue method; there's no input validation but format strings are provided to ensure the correct time-to-string conversion.

t := time.Now()
f0.SetValue(t.Format(fields.DATETIME_FORMAT))
f1.SetValue(t.Format(fields.DATE_FORMAT))
f2.SetValue(t.Format(fields.TIME_FORMAT))

Buttons

Buttons can be created calling either the Button, SubmitButton or ResetButton constructor methods and providing a text identifier and the content of the button itself.

btn0 := fields.Button("btn", "Click me!")

License

forms is released under the MIT license. See LICENSE.

Documentation

Overview

Package forms 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.

Copyright 2016-present Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2016-present Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Copyright 2016-present Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Index

Constants

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

Form methods: POST or GET.

Variables

This section is empty.

Functions

func GenChoices added in v1.4.0

func GenChoices(lenType interface{}, fnType interface{}) interface{}

GenChoices generate choices

type Data struct{
	ID string
	Name string
}
data:=[]*Data{
	&Data{ID:"a",Name:"One"},
	&Data{ID:"b",Name:"Two"},
}
GenChoices(len(data), func(index int) (string, string, bool){
	return data[index].ID,data[index].Name,false
})

or

GenChoices(map[string]int{
	"":len(data),
}, func(group string,index int) (string, string, bool){
	return data[index].ID,data[index].Name,false
})

func Html5Validate added in v1.2.1

func Html5Validate(valid string, f fields.FieldInterface)

func NewConfig added in v1.4.0

func NewConfig() *config.Config

func Unmarshal added in v1.4.0

func Unmarshal(b []byte, key string) (r *config.Config, err error)

func UnmarshalFile added in v1.4.2

func UnmarshalFile(filename string) (r *config.Config, err error)

func ValidationEngine added in v1.2.1

func ValidationEngine(valid string, f fields.FieldInterface)

Types

type ElementSetter added in v1.4.0

type ElementSetter interface {
	Elements(...config.FormElement)
}

type FieldSetType

type FieldSetType struct {
	OrigName   string                  `json:"origName" xml:"origName"`
	CurrName   string                  `json:"currName" xml:"currName"`
	Label      string                  `json:"label" xml:"label"`
	LabelCols  int                     `json:"labelCols" xml:"labelCols"`
	FieldCols  int                     `json:"fieldCols" xml:"fieldCols"`
	Classes    common.HTMLAttrValues   `json:"classes" xml:"classes"`
	Tags       common.HTMLAttrValues   `json:"tags" xml:"tags"`
	FieldList  []fields.FieldInterface `json:"fieldList" xml:"fieldList"`
	AppendData map[string]interface{}  `json:"appendData,omitempty" xml:"appendData,omitempty"`
	FormTheme  string                  `json:"formTheme" xml:"formTheme"`
	Language   string                  `json:"language,omitempty" xml:"language,omitempty"`
	Template   string                  `json:"template" xml:"template"`
	// contains filtered or unexported fields
}

FieldSetType is a collection of fields grouped within a form.

func FieldSet

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

FieldSet creates and returns a new FieldSetType with the given name and list of fields. 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) Clone added in v1.4.0

func (f *FieldSetType) Clone() config.FormElement

func (*FieldSetType) Data added in v1.3.1

func (f *FieldSetType) Data() map[string]interface{}

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) Elements

func (f *FieldSetType) Elements(elems ...config.FormElement) *FieldSetType

Elements adds the provided elements to the fieldset.

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) fields.FieldInterface

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

func (*FieldSetType) Lang added in v1.4.0

func (f *FieldSetType) Lang() string

func (*FieldSetType) Name

func (f *FieldSetType) Name() string

Name returns the name of the fieldset.

func (*FieldSetType) OriginalName added in v1.4.0

func (f *FieldSetType) OriginalName() string

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() template.HTML

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

func (*FieldSetType) SetData

func (f *FieldSetType) SetData(key string, value interface{})

func (*FieldSetType) SetFieldCols added in v1.7.0

func (f *FieldSetType) SetFieldCols(cols int)

func (*FieldSetType) SetLabelCols added in v1.7.0

func (f *FieldSetType) SetLabelCols(cols int)

func (*FieldSetType) SetLang added in v1.4.0

func (f *FieldSetType) SetLang(lang string)

func (*FieldSetType) SetName added in v1.4.0

func (f *FieldSetType) SetName(name string)

func (*FieldSetType) SetTemplate added in v1.8.0

func (f *FieldSetType) SetTemplate(tmpl string) *FieldSetType

func (*FieldSetType) Sort

func (f *FieldSetType) Sort(sortList ...string) *FieldSetType

Sort("field1:1,field2:2") or Sort("field1:1","field2:2")

func (*FieldSetType) Sort2Last added in v1.3.1

func (f *FieldSetType) Sort2Last(fieldsName ...string) *FieldSetType

func (*FieldSetType) SortAll

func (f *FieldSetType) SortAll(sortList ...string) *FieldSetType

SortAll("field1,field2") or SortAll("field1","field2")

func (*FieldSetType) String

func (f *FieldSetType) String() string

type Form

type Form struct {
	AppendData map[string]interface{} `json:"appendData,omitempty" xml:"appendData,omitempty"`
	Model      interface{}            `json:"model" xml:"model"`
	FieldList  []config.FormElement   `json:"fieldList" xml:"fieldList"`
	Theme      string                 `json:"theme" xml:"theme"`
	Class      common.HTMLAttrValues  `json:"class" xml:"class"`
	ID         string                 `json:"id" xml:"id"`
	Params     map[string]string      `json:"params" xml:"params"`
	CSS        map[string]string      `json:"css" xml:"css"`
	Method     string                 `json:"method" xml:"method"`
	Action     template.HTML          `json:"action" xml:"action"`
	// contains filtered or unexported fields
}

Form structure.

func New added in v1.4.0

func New() *Form

func NewFromModel added in v1.4.0

func NewFromModel(m interface{}, c *config.Config) *Form

func NewWithConfig added in v1.4.0

func NewWithConfig(c *config.Config, args ...interface{}) *Form

func NewWithConfigFile added in v1.4.0

func NewWithConfigFile(m interface{}, configJSONFile string) *Form

func NewWithModelConfig added in v1.4.0

func NewWithModelConfig(m interface{}, r *config.Config) *Form

func (*Form) AddBeforeRender added in v1.4.0

func (f *Form) AddBeforeRender(fn func()) *Form

func (*Form) AddButton added in v1.4.0

func (f *Form) AddButton(tmpl string, args ...string) *Form

func (*Form) AddCSS added in v1.4.0

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) AddClass

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

AddClass associates the provided class to the Form.

func (*Form) CloseValid added in v1.4.0

func (form *Form) CloseValid(fieldName ...string) *Form

func (*Form) Config added in v1.8.2

func (f *Form) Config() *config.Config

func (*Form) Data added in v1.3.1

func (f *Form) Data() map[string]interface{}

func (*Form) Debug added in v1.4.0

func (f *Form) Debug(args ...bool) *Form

func (*Form) DeleteParam

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

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

func (*Form) Elements

func (f *Form) Elements(elems ...config.FormElement)

Elements adds the provided elements to the form.

func (*Form) Error added in v1.4.0

func (f *Form) Error() (err *validation.ValidationError)

func (*Form) Errors added in v1.4.0

func (f *Form) Errors() (errs []*validation.ValidationError)

func (*Form) Field

func (f *Form) Field(name string) fields.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

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

func (*Form) Fields added in v1.3.1

func (f *Form) Fields() []config.FormElement

Fields returns all field

func (*Form) Filter added in v1.4.0

func (form *Form) Filter(values url.Values) (url.Values, *validation.ValidationError)

Filter 过滤客户端提交的数据

func (*Form) FilterByElement added in v1.4.0

func (form *Form) FilterByElement(input url.Values, output url.Values, ele *config.Element) (url.Values, *validation.ValidationError)

FilterByElement 过滤单个元素

func (*Form) GenChoices added in v1.4.0

func (f *Form) GenChoices(lenType interface{}, fnType interface{}) interface{}

GenChoices generate choices

type Data struct{
	ID string
	Name string
}

data:=[]*Data{
	&Data{ID:"a",Name:"One"},
	&Data{ID:"b",Name:"Two"},
}

GenChoices(len(data), func(index int) (string, string, bool){
	return data[index].ID,data[index].Name,false
})

or

GenChoices(map[string]int{
	"":len(data),
}, func(group string,index int) (string, string, bool){

	return data[index].ID,data[index].Name,false
})

func (*Form) GenChoicesForField added in v1.4.0

func (f *Form) GenChoicesForField(name string, lenType interface{}, fnType interface{}) *Form

func (*Form) Generate added in v1.4.0

func (form *Form) Generate(m interface{}, jsonFile string) error

func (*Form) HTMLTemplate added in v1.8.9

func (f *Form) HTMLTemplate() (*template.Template, error)

func (*Form) HasError added in v1.4.0

func (f *Form) HasError() bool

func (*Form) HasErrors added in v1.4.0

func (f *Form) HasErrors() bool

func (*Form) Init added in v1.4.0

func (f *Form) Init(c *config.Config, model ...interface{}) *Form

func (*Form) InsertErrors added in v1.4.0

func (f *Form) InsertErrors() *Form

func (*Form) IsDebug added in v1.4.0

func (f *Form) IsDebug() bool

func (*Form) IsIgnored added in v1.4.0

func (form *Form) IsIgnored(fieldName string) bool

func (*Form) IsOmit added in v1.4.0

func (f *Form) IsOmit(fieldName string) (omitFieldValue bool)

IsOmit 是否忽略结构体实例中指定字段的值

func (*Form) LabelFunc added in v1.4.0

func (f *Form) LabelFunc() func(string) string

func (*Form) LangSet added in v1.4.0

func (f *Form) LangSet(name string) *LangSetType

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

func (*Form) Must added in v1.4.0

func (f *Form) Must(fields ...string) *Form

Must 使用结构体实例中某些字段的值(和OmitAll配合起来使用)

func (*Form) NewConfig added in v1.4.0

func (form *Form) NewConfig() *config.Config

func (*Form) NewFieldSet

func (f *Form) NewFieldSet(name string, label string, elems ...fields.FieldInterface) *FieldSetType

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

func (*Form) NewLangSet added in v1.4.0

func (f *Form) NewLangSet(name string, langs []*config.Language) *LangSetType

func (*Form) Omit added in v1.4.0

func (f *Form) Omit(fields ...string) *Form

Omit 忽略结构体实例中某些字段的值

func (*Form) OmitAll added in v1.4.0

func (f *Form) OmitAll(on ...bool) *Form

OmitAll 忽略结构体实例中所有字段的值

func (*Form) ParseElements added in v1.4.0

func (form *Form) ParseElements(es ElementSetter, elements []*config.Element, langs []*config.Language, t reflect.Type, v reflect.Value, lang string)

func (*Form) ParseFromConfig added in v1.4.0

func (form *Form) ParseFromConfig(insertErrors ...bool) *Form

func (*Form) ParseFromJSON added in v1.4.2

func (form *Form) ParseFromJSON(b []byte, key string) error

func (*Form) ParseFromJSONFile added in v1.4.2

func (form *Form) ParseFromJSONFile(jsonFile string) error

func (*Form) ParseModel added in v1.4.0

func (f *Form) ParseModel(model ...interface{}) *Form

func (*Form) RemoveCSS added in v1.4.0

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

RemoveCSS removes CSS style from the form.

func (*Form) RemoveClass

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

RemoveClass removes the given class (if present) 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() 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) ResetOmitOrMust added in v1.4.0

func (f *Form) ResetOmitOrMust() *Form

func (*Form) SetData

func (f *Form) SetData(key string, value interface{})

func (*Form) SetID added in v1.4.0

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

SetID set the given id to the form.

func (*Form) SetLabelFunc added in v1.4.0

func (f *Form) SetLabelFunc(fn func(string) string) *Form

func (*Form) SetModel added in v1.3.1

func (f *Form) SetModel(m interface{}) *Form

func (*Form) SetParam

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

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

func (*Form) SetValidTagFunc added in v1.4.0

func (f *Form) SetValidTagFunc(fn func(string, fields.FieldInterface)) *Form

func (*Form) Sort

func (f *Form) Sort(sortList ...string) *Form

Sort Sort("field1:1,field2:2") or Sort("field1:1","field2:2")

func (*Form) Sort2Last added in v1.3.1

func (f *Form) Sort2Last(fieldsName ...string) *Form

func (*Form) SortAll

func (f *Form) SortAll(sortList ...string) *Form

SortAll SortAll("field1,field2") or SortAll("field1","field2")

func (*Form) String

func (f *Form) String() string

func (*Form) ToConfig added in v1.4.0

func (form *Form) ToConfig() *config.Config

func (*Form) ToHTML added in v1.8.9

func (f *Form) ToHTML(value interface{}) template.HTML

func (*Form) ToJSONBlob added in v1.4.0

func (form *Form) ToJSONBlob(args ...*config.Config) (r []byte, err error)

func (*Form) Valid added in v1.3.1

func (f *Form) Valid(onlyCheckFields ...string) error

func (*Form) ValidElements added in v1.4.0

func (form *Form) ValidElements(elements []*config.Element, t reflect.Type, v reflect.Value)

func (*Form) ValidFromConfig added in v1.4.0

func (form *Form) ValidFromConfig() *Form

func (*Form) ValidFromJSON added in v1.4.2

func (form *Form) ValidFromJSON(b []byte, key string) error

func (*Form) ValidFromJSONFile added in v1.4.2

func (form *Form) ValidFromJSONFile(jsonFile string) error

func (*Form) ValidTagFunc added in v1.4.0

func (f *Form) ValidTagFunc() func(string, fields.FieldInterface)

func (*Form) Validate added in v1.4.0

func (f *Form) Validate() *validation.Validation

type Forms added in v1.4.0

type Forms struct {
	*Form
}

func NewForms added in v1.4.0

func NewForms(f *Form) *Forms

func (*Forms) MarshalJSON added in v1.4.0

func (f *Forms) MarshalJSON() ([]byte, error)

MarshalJSON allows type Pagination to be used with json.Marshal

func (*Forms) MarshalXML added in v1.4.0

func (f *Forms) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type Pagination to be used with xml.Marshal

type LangSetType added in v1.4.0

type LangSetType struct {
	Languages  []*config.Language     `json:"languages" xml:"languages"`
	CurrName   string                 `json:"currName" xml:"currName"`
	OrigName   string                 `json:"origName" xml:"origName"`
	Template   string                 `json:"template" xml:"template"`
	Params     map[string]interface{} `json:"params" xml:"params"`
	Tags       common.HTMLAttrValues  `json:"tags" xml:"tags"`
	AppendData map[string]interface{} `json:"appendData,omitempty" xml:"appendData,omitempty"`
	Alone      bool                   `json:"alone,omitempty" xml:"alone,omitempty"`
	FormTheme  string                 `json:"formTheme" xml:"formTheme"`
	// contains filtered or unexported fields
}

LangSetType is a collection of fields grouped within a form.

func LangSet added in v1.4.0

func LangSet(name string, theme string, languages ...*config.Language) *LangSetType

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

func (*LangSetType) AddLanguage added in v1.4.0

func (f *LangSetType) AddLanguage(language *config.Language)

func (*LangSetType) AddTag added in v1.4.0

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

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

func (*LangSetType) Clone added in v1.4.0

func (f *LangSetType) Clone() config.FormElement

func (*LangSetType) Data added in v1.4.0

func (f *LangSetType) Data() map[string]interface{}

func (*LangSetType) DeleteParam added in v1.4.0

func (f *LangSetType) DeleteParam(k string) *LangSetType

DeleteParam removes the provided param from the langset, if it was present. Nothing is done if it was not originally present.

func (*LangSetType) Disable added in v1.4.0

func (f *LangSetType) Disable() *LangSetType

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

func (*LangSetType) Elements added in v1.4.0

func (f *LangSetType) Elements(elems ...config.FormElement)

Elements adds the provided elements to the langset.

func (*LangSetType) Enable added in v1.4.0

func (f *LangSetType) Enable() *LangSetType

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

func (*LangSetType) Field added in v1.4.0

func (f *LangSetType) Field(name string) fields.FieldInterface

Field returns the field identified by name. It returns an empty field if it is missing. param format: "language:name"

func (*LangSetType) FieldSet added in v1.4.0

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

FieldSet returns the fieldset identified by name. param format: "language:name"

func (*LangSetType) Lang added in v1.4.0

func (f *LangSetType) Lang() string

func (*LangSetType) Language added in v1.4.0

func (f *LangSetType) Language(lang string) *config.Language

func (*LangSetType) Name added in v1.4.0

func (f *LangSetType) Name() string

Name returns the name of the langset.

func (*LangSetType) NewFieldSet added in v1.4.0

func (f *LangSetType) NewFieldSet(name string, label string, elems ...fields.FieldInterface) *FieldSetType

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

func (*LangSetType) OriginalName added in v1.4.0

func (f *LangSetType) OriginalName() string

func (*LangSetType) RemoveTag added in v1.4.0

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

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

func (*LangSetType) Render added in v1.4.0

func (f *LangSetType) Render() template.HTML

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

func (*LangSetType) SetData added in v1.4.0

func (f *LangSetType) SetData(key string, value interface{})

func (*LangSetType) SetLang added in v1.4.0

func (f *LangSetType) SetLang(lang string)

func (*LangSetType) SetName added in v1.4.0

func (f *LangSetType) SetName(name string)

func (*LangSetType) SetParam added in v1.4.0

func (f *LangSetType) SetParam(k string, v interface{}) *LangSetType

SetParam saves the provided param for the langset.

func (*LangSetType) SetTemplate added in v1.8.0

func (f *LangSetType) SetTemplate(tmpl string) *LangSetType

func (*LangSetType) Sort added in v1.4.0

func (f *LangSetType) Sort(sortList ...string) *LangSetType

Sort Sort("field1:1,field2:2") or Sort("field1:1","field2:2")

func (*LangSetType) Sort2Last added in v1.4.0

func (f *LangSetType) Sort2Last(fieldsName ...string) *LangSetType

func (*LangSetType) SortAll added in v1.4.0

func (f *LangSetType) SortAll(sortList ...string) *LangSetType

SortAll("field1,field2") or SortAll("field1","field2")

func (*LangSetType) String added in v1.4.0

func (f *LangSetType) String() string

Directories

Path Synopsis
Package common This package provides basic constants used by forms packages.
Package common This package provides basic constants used by forms packages.
Package fields This package provides all the input fields logic and customization methods.
Package fields This package provides all the input fields logic and customization methods.
Package widgets This package contains the base logic for the creation and rendering of field widgets.
Package widgets This package contains the base logic for the creation and rendering of field widgets.

Jump to

Keyboard shortcuts

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