Skip to content

Commit 75c9c5b

Browse files
Support multiple forms on a single page.
1 parent f634285 commit 75c9c5b

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

pkg/form/form.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import (
99
type Form interface {
1010
// Submit marks the form as submitted, stores a pointer to it in the context, binds the request
1111
// values to the struct fields, and validates the input based on the struct tags.
12-
// Returns a validator.ValidationErrors if the form values were not valid.
13-
// Returns an echo.HTTPError if the request failed to process.
12+
// Returns a validator.ValidationErrors, if the form values were not valid, or an echo.HTTPError,
13+
// if the request failed to process.
1414
Submit(c echo.Context, form any) error
1515

1616
// IsSubmitted returns true if the form was submitted.
@@ -35,7 +35,9 @@ type Form interface {
3535
// Get gets a form from the context or initializes a new copy if one is not set.
3636
func Get[T any](ctx echo.Context) *T {
3737
if v := ctx.Get(context.FormKey); v != nil {
38-
return v.(*T)
38+
if form, ok := v.(*T); ok {
39+
return form
40+
}
3941
}
4042
var v T
4143
return &v

pkg/form/form_test.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func TestGetClear(t *testing.T) {
3636
}
3737

3838
t.Run("get empty context", func(t *testing.T) {
39-
// Empty context, still return a form
39+
// Empty context, still return a form.
4040
ctx, _ := tests.NewContext(e, "/")
4141
form := Get[example](ctx)
4242
assert.NotNil(t, form)
@@ -49,12 +49,16 @@ func TestGetClear(t *testing.T) {
4949
ctx, _ := tests.NewContext(e, "/")
5050
ctx.Set(context.FormKey, &form)
5151

52-
// Get again and expect the values were stored
52+
// Get again and expect the values were stored.
5353
got := Get[example](ctx)
5454
require.NotNil(t, got)
55-
assert.Equal(t, "test", form.Name)
55+
assert.Equal(t, "test", got.Name)
5656

57-
// Clear
57+
// Attempt getting a different type to ensure there's no panic.
58+
ret := Get[int](ctx)
59+
require.NotNil(t, ret)
60+
61+
// Clear.
5862
Clear(ctx)
5963
got = Get[example](ctx)
6064
require.NotNil(t, got)

0 commit comments

Comments
 (0)