Skip to content
Gx
GitHub

GX2023: form of a route type with no key field renders in a loop

A form of a route type renders one time for each row, and the route type has no key field.

Cause

A form of a route type renders in a loop, and the route type has no key field. Each form then has the same id, and each field has the same id too. The HTML is not valid, and a label points at the field of the first row only. When a submit fails a rule, the patch goes to the first form of the page and not to the form that the reader submitted.

The finding is a hint. It does not fail gx check.

Example

sessions/route/route.go
package route

import "github.com/alternayte/gx"

type Revoke struct {
	gx.Route `POST /sessions/revoke`
	ID       string
}

func (in *Revoke) Rules() gx.Rules {
	return gx.Rules{gx.Field(&in.ID, gx.Required)}
}
sessions/List.gx
package sessions

import "app/sessions/route"

props {
  Rows []route.RevokeForm
}

<ul>
  for i, f := range p.Rows {
    <li key={i}>
      <form {...f.Attrs()}>
        <input type="hidden" {...f.ID.Attrs()} />
        <button type="submit">Revoke</button>
      </form>
    </li>
  }
</ul>

gx check reports:

gx check
sessions/List.gx:12:7: GX2023: hint: a form of "Revoke" renders in a loop, and the route type has no key field: each form gets the same ids

Fix

Add the tag gx:"key" to the field that is different for each form:

type Revoke struct {
	gx.Route `POST /sessions/revoke`
	ID       string `gx:"key"`
}

The id of the form is then revoke-form-<key>, and the id of each field is revoke-<key>-<field>. A failed submit binds the same key, so the patch goes to the correct form.