From 67a97832a5127e47e529bfa9208513b7e694320b Mon Sep 17 00:00:00 2001 From: mikestefanello <552328+mikestefanello@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:55:29 -0400 Subject: [PATCH] Support multiple forms on a single page. --- pkg/form/form.go | 8 +++++--- pkg/form/form_test.go | 12 ++++++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/pkg/form/form.go b/pkg/form/form.go index 16177e1..bdd5ada 100644 --- a/pkg/form/form.go +++ b/pkg/form/form.go @@ -9,8 +9,8 @@ import ( type Form interface { // Submit marks the form as submitted, stores a pointer to it in the context, binds the request // values to the struct fields, and validates the input based on the struct tags. - // Returns a validator.ValidationErrors if the form values were not valid. - // Returns an echo.HTTPError if the request failed to process. + // Returns a validator.ValidationErrors, if the form values were not valid, or an echo.HTTPError, + // if the request failed to process. Submit(c echo.Context, form any) error // IsSubmitted returns true if the form was submitted. @@ -35,7 +35,9 @@ type Form interface { // Get gets a form from the context or initializes a new copy if one is not set. func Get[T any](ctx echo.Context) *T { if v := ctx.Get(context.FormKey); v != nil { - return v.(*T) + if form, ok := v.(*T); ok { + return form + } } var v T return &v diff --git a/pkg/form/form_test.go b/pkg/form/form_test.go index c297150..cbd957d 100644 --- a/pkg/form/form_test.go +++ b/pkg/form/form_test.go @@ -36,7 +36,7 @@ func TestGetClear(t *testing.T) { } t.Run("get empty context", func(t *testing.T) { - // Empty context, still return a form + // Empty context, still return a form. ctx, _ := tests.NewContext(e, "/") form := Get[example](ctx) assert.NotNil(t, form) @@ -49,12 +49,16 @@ func TestGetClear(t *testing.T) { ctx, _ := tests.NewContext(e, "/") ctx.Set(context.FormKey, &form) - // Get again and expect the values were stored + // Get again and expect the values were stored. got := Get[example](ctx) require.NotNil(t, got) - assert.Equal(t, "test", form.Name) + assert.Equal(t, "test", got.Name) - // Clear + // Attempt getting a different type to ensure there's no panic. + ret := Get[int](ctx) + require.NotNil(t, ret) + + // Clear. Clear(ctx) got = Get[example](ctx) require.NotNil(t, got)