Skip to content

Building a form

Build a settings form: enter a name, select a language, accept the terms, and save.

1. Run the example

go
package main

import (
	"github.com/dxui-org/dxui"
	"log"
	"strings"
)

func main() {
	name, language, message := "", "go", "Fill in the form"
	accepted := false
	valid := func() bool {
		return strings.TrimSpace(name) != "" && accepted
	}
	submit := func() {
		if valid() {
			message = "Saved: " + name + " / " + language
		}
	}
	app := dxui.NewApp(dxui.AppOptions{
		Background: dxui.RGBA(248, 250, 252, 255),
		Title:      "Preferences",
		Width:      640,
		Height:     480,
	})
	if err := app.Run(func() dxui.View {
		return dxui.Box(
			dxui.BoxProps{
				Gap: 16,
				Style: dxui.Style{
					Padding: dxui.Padding(24),
					Width:   dxui.Px(400),
				},
			},
			dxui.Input(dxui.InputProps{
				Key:         "name",
				Value:       name,
				Placeholder: "Name",
				OnChange:    dxui.Assign(&name),
				OnSubmit:    submit,
			}),
			dxui.Select(dxui.SelectProps{
				Value:    language,
				OnChange: dxui.Assign(&language),
				Options: []dxui.SelectOption{
					{
						Value: "go",
						Label: "Go",
					},
					{
						Value: "rust",
						Label: "Rust",
					},
				},
			}),
			dxui.Checkbox(
				dxui.CheckboxProps{
					Checked:  accepted,
					OnChange: dxui.Assign(&accepted),
				},
				dxui.Label("Accept terms"),
			),
			dxui.TextButton(
				dxui.ButtonProps{
					Disabled: !valid(),
					OnPress:  submit,
				},
				"Save",
			),
			dxui.Label(message),
		)
	}); err != nil {
		log.Fatal(err)
	}
}

2. Try it in order

  1. Leave the name empty and observe that Save is disabled.
  2. Enter a name, choose a language, and check Accept terms.
  3. Click Save to display Saved: .... Pressing Enter in the name input also submits.
  4. Clear the name or uncheck the terms; Save becomes disabled again.

Saving in this example updates text only; it does not write a file.

3. Understand the form logic

CodePurpose
name, language, acceptedStore the three control values.
OnChange: dxui.Assign(...)Writes changes into the corresponding variable.
valid()Checks for a nonempty name and accepted terms.
Disabled: !valid()Disables Save while the conditions are unmet.
submit()Rechecks conditions, then updates the message.

Both the button and input Enter action call submit, so validate inside that function instead of relying only on the disabled button.

Try requiring at least two characters in valid(), then submit through both the button and Enter.

For additional configuration, see Input, Select, and Checkbox.

Next: Run background tasks.