Workflow

Workflow

Import

import (
    "html/template"
	"net/http"

    "gitnet.fr/deblan/go-form/form"
    "gitnet.fr/deblan/go-form/theme"
)

Create a form

// Let's create a new form
// You can pass *form.Field as arguments
myForm := form.NewForm(field1, field2, ...)

// Add somes fields
myForm.Add(field3, field4, ...)

// Set the method
// <form method="POST" ...>
myForm.WithMethod(http.MethodPost)

// Define the action
// <form action="/" ...>
myForm.WithAction("/")

// Set a name
myForm.WithName("myForm")

// Add options
myForm.WithOptions(option1, option2, ...)

// When all fields are added, call End()
myForm.End()

Attributes

Some options are natively supported in go-form themes.

myForm.WithOptions(
    form.NewOption("help", "A help for the form"),
    // <form data-foo="bar" data-bar="bar" ...
    form.NewOption("attr", form.Attrs{
        "data-foo": "foo",
        "data-bar": "bar",
    }),
)

Data mounting

This step is not required when you does not want to pre-fill the form. Your struct can be complexe and the form only map existing properties.

type Person struct {
    Name string
    Age  int
}

data := Person{
    Name: "Alice",
    Age:  42,
}

// Assuming 2 fields named "Name" and "Age" exist
myForm.Mount(data)

Rendering

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // myForm := form.NewForm(...)

    render := theme.NewRenderer(theme.Html5)
    tpl, _ := template.New("page").Funcs(render.FuncMap()).Parse(`{{ form .Form }}`)

    w.Header().Set("Content-Type", "text/html; charset=utf-8")

    tpl.Execute(w, map[string]any{
        "Form": myForm,
    })
}

Data binding

This is the final step. After the form handles the request, you can check if the form has been submitted, check the values are valid and finally populate your struct.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // data := Person{...}
    // myForm := form.NewForm(...)

    if r.Method == myForm.Method {
        myForm.HandleRequest(r)

        if myForm.IsSubmitted() && myForm.IsValid() {
            myForm.Bind(&data)
        }
    }
})