jsonform

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2025 License: MIT Imports: 16 Imported by: 1

README

jsonform-go

Build Status Coverage Status GoDevDoc Time Tracker Code lines Comments

This library renders HTML form from JSON Schema field tags of a Go structure. It is based on github.com/jsonform/jsonform JS library.

Usage

See full example.

Define or instrument existing structure with JSON schema field tags and with form item field tags.

type User struct {
	FirstName string     `json:"firstName" required:"true" title:"First name" minLength:"3"`
	LastName  string     `json:"lastName" required:"true" title:"Last name" minLength:"3"`
	Locale    string     `json:"locale" title:"User locale" enum:"ru-RU,en-US"`
	Age       int        `json:"age" title:"Age" minimum:"1"`
	Status    userStatus `json:"status" title:"Status"`
	Bio       string     `json:"bio" title:"Bio" description:"A brief description of the person." formType:"textarea"`
}

Create form repository and add schemas.

jf := jsonform.NewRepository(&jsonschema.Reflector{})
err := jf.Add(User{})

Mount handlers with static assets and schemas to *web.Service.

jf.Mount(s, "/json-form/")
Dynamic Forms

Form can be rendered using ./form.html and query parameters.

{String} title - Title of the form.
{String} schemaName - Schema name.
{String} valueUrl - URL to fetch value.
{String} submitUrl - URL to submit form.
{String} submitMethod - HTTP method to use on form submit.
{Number} successStatus - Success HTTP status code to expect on submit.

Examples:

/json-form/form.html?title=Create%20user&schemaName=user&submitUrl=/users&submitMethod=POST&successStatus=201
/json-form/form.html?title=Edit%20user&schemaName=user&valueUrl=/user/1.json&submitUrl=/user/1.json&submitMethod=PUT&successStatus=204
Static Forms

For more user-friendly URLs, multiple forms on page and other page customizations you can use Render to create web pages with forms.

repo.Render(output.Writer, jsonform.Page{}, jsonform.Form{
    Title:         "Update User",
    SubmitMethod:  http.MethodPut,
    SubmitURL:     "/user/" + strconv.Itoa(input.ID) + ".json",
    Value:         user,
    SuccessStatus: http.StatusNoContent,
}
Form Field Tags
  • formType, values "textarea","password","wysihtml5","submit","color","checkboxes","radios","fieldset", "help", "hidden", "ace"
  • formTitle example "Submit"
  • readOnly example "true"
  • prepend example "I feel"
  • append example "today"
  • noTitle example "true"
  • htmlClass example "usermood"
  • fieldHTMLClass example "input-xxlarge"
  • placeholder example "incredibly and admirably great"
  • inlineTitle example "Check this box if you are over 18"
  • activeClass example "btn-success", button mode for radio buttons
  • helpValue example "<strong>Click me!</strong>"

Documentation

Overview

Package jsonform provides JSON Schema HTML form renderer.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Form added in v0.2.0

type Form struct {
	Title         string `json:"title,omitempty"`
	Description   string `json:"description,omitempty"`
	SchemaName    string `json:"schemaName,omitempty"`
	ValueURL      string `json:"valueUrl,omitempty"`
	SubmitURL     string `json:"submitUrl,omitempty"`
	SubmitMethod  string `json:"submitMethod,omitempty"`
	SuccessStatus int    `json:"successStatus,omitempty"`

	// OnSuccess is a javascript callback that receives XMLHttpRequest value in case of successful response.
	OnSuccess template.JS `json:"-"`
	// OnFail is a javascript callback that receives XMLHttpRequest value in case of a failure response.
	OnFail template.JS `json:"-"`
	// OnError is a javascript callback that receives string HTML value in case of an error while processing the form.
	OnError template.JS `json:"-"`
	// OnBeforeSubmit is a javascript callback that receives form data after Submit button is clicked and before request is sent.
	OnBeforeSubmit template.JS `json:"-"`
	// OnRequestFinished is a javascript callback that receives XMLHttpRequest after request is finished.
	OnRequestFinished template.JS `json:"-"`

	Schema *FormSchema `json:"schema,omitempty"`
	Value  interface{} `json:"value,omitempty"`

	// SubmitText is an optional description of submit button.
	SubmitText string `json:"-"`
}

Form describes form parameters.

type FormItem

type FormItem struct {
	Key       string     `json:"key,omitempty" example:"longmood"`
	FormType  string     `` /* 176-byte string literal not displayed */
	FormTitle string     `json:"title,omitempty" example:"Submit"`
	Items     []FormItem `json:"items,omitempty"`

	ReadOnly bool `json:"readonly,omitempty"`

	Prepend        string            `json:"prepend,omitempty" example:"I feel"`
	Append         string            `json:"append,omitempty" example:"today"`
	NoTitle        bool              `json:"notitle,omitempty"`
	HtmlClass      string            `json:"htmlClass,omitempty" example:"usermood"`
	HtmlMetaData   map[string]string `json:"htmlMetaData,omitempty" example:"{\"style\":\"border: 1px solid blue\",\"data-title\":\"Mood\"}"`
	FieldHtmlClass string            `json:"fieldHtmlClass,omitempty" example:"input-xxlarge"`
	Placeholder    string            `json:"placeholder,omitempty" example:"incredibly and admirably great"`
	InlineTitle    string            `json:"inlinetitle,omitempty" example:"Check this box if you are over 18"`
	TitleMap       map[string]string `json:"titleMap,omitempty" description:"Title mapping for enum."`
	ActiveClass    string            `json:"activeClass,omitempty" example:"btn-success" description:"Button mode for radio buttons."`
	HelpValue      string            `json:"helpvalue,omitempty" example:"<strong>Click me!</strong>"`

	AceMode  string `json:"aceMode,omitempty" example:"json"`
	AceTheme string `json:"aceTheme,omitempty" example:"twilight"`
}

FormItem defines form item rendering parameters.

type FormSchema

type FormSchema struct {
	Form   []FormItem        `json:"form,omitempty"`
	Schema jsonschema.Schema `json:"schema"`
}

FormSchema describes form elements.

type Page added in v0.2.0

type Page struct {
	// AppendHTMLHead is injected into the <head> of an HTML document.
	AppendHTMLHead template.HTML

	// PrependHTML is added before the forms.
	PrependHTML template.HTML

	// AppendHTML is added after the forms.
	AppendHTML template.HTML

	// Title is set to HTML document title.
	Title string
}

Page allows page customizations.

type Repository

type Repository struct {
	// Strict requires all schemas to be added in advance.
	Strict bool
	// contains filtered or unexported fields
}

Repository manages form schemas and provides integration helpers.

func NewRepository

func NewRepository(reflector *jsonschema.Reflector) *Repository

NewRepository creates schema repository.

func (*Repository) Add added in v0.2.0

func (r *Repository) Add(values ...interface{}) error

Add adds schemas of value samples. It stops on the first error.

func (*Repository) AddNamed added in v0.2.0

func (r *Repository) AddNamed(value interface{}, name string) error

AddNamed registers schema with custom name, this is not needed if default name is good enough.

func (*Repository) GetSchema

func (r *Repository) GetSchema() usecase.Interactor

GetSchema returns JSONForm schema.

func (*Repository) Mount

func (r *Repository) Mount(s *web.Service, prefix string)

Mount attaches handlers to web service.

func (*Repository) Name added in v0.2.0

func (r *Repository) Name(value interface{}) string

Name returns schema name by sample value.

func (*Repository) Names added in v0.2.0

func (r *Repository) Names() []string

Names returns names of added schemas.

func (*Repository) Render added in v0.2.0

func (r *Repository) Render(w io.Writer, p Page, forms ...Form) error

Render renders forms as web page.

func (*Repository) Schema

func (r *Repository) Schema(value interface{}) *FormSchema

Schema returns previously added schema by its sample value. It returns nil for unknown schema.

func (*Repository) SchemaByName added in v0.2.0

func (r *Repository) SchemaByName(name string) *FormSchema

SchemaByName return previously added schema by its name. It returns nil for unknown schema.

Jump to

Keyboard shortcuts

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