feat(12.1-02): password and form-only fields, rules per operation and preset

- pact.FormVirtualFields lists form fields that are not model columns: never
  bound, filled or projected; their values reach the Form hooks through
  cabana.VirtualFieldsFromContext when the field's context allows the operation
- type: password is a masked field that must be listed as virtual
- pact.FormRules supplies the rule set per operation and replaces the model's
  Rules() for admin saves; a rule on a virtual field sees the submitted value
- preset on a text field follows another text field on the create form
- SPA: PasswordField, preset handling in FormView, empty password left out of
  an update
- README, docs, OpenAPI document, TS types and dist updated
This commit is contained in:
Jakub Zych
2026-10-05 10:35:08 +02:00
parent a65c670574
commit a1c6bb1ce6
42 changed files with 1284 additions and 49 deletions

View File

@@ -221,6 +221,47 @@ A hook or scope that has to read the database during a write should use the tran
Scope reads and writes with `pact.ListExtendQuery` and `pact.FormExtendQuery` rather than checking in a hook: the scope then applies to every route, including relation and action routes.
### Form-only values and rules
A form may collect values that are not columns of the record (see [Form-only fields](forms.md#form-only-fields)). The Form hooks read what the administrator submitted with `cabana.VirtualFieldsFromContext(ctx)`. The map holds only the fields that were sent and that the field's `context` allows for this operation, so a missing key means "not submitted". Values are scalars as decoded from the request: a string, a bool, a `json.Number` or nil. The map is a copy, and the second result is false outside a create or update.
```go src=modules/cabana/example_form_seams_test.go#MembersController.FormBeforeCreate
// FormBeforeCreate reads the submitted virtual values, which have passed the
// rules by now, and stores what the model needs.
func (MembersController) FormBeforeCreate(ctx context.Context, model any) error {
values, _ := cabana.VirtualFieldsFromContext(ctx)
member := model.(*Member)
if plain, ok := values["password"].(string); ok && plain != "" {
member.Password = hashPassword(plain)
}
if notify, _ := values["notify"].(bool); notify {
// Queue the welcome message here.
}
return nil
}
```
A save validates the record against the model's `Rules()`. Those are often the rules of a public sign-up, which an admin form cannot meet: an update that changes only a name would have to repeat the password. A controller implementing `pact.FormRules` returns the rules of an admin save for `create` or `update`, and that set replaces the model's:
```go src=modules/cabana/example_form_seams_test.go#MembersController.FormRules
// FormRules replaces the model's rules for admin saves: a create needs a
// password, an update takes one only when the administrator types it.
func (MembersController) FormRules(_ context.Context, op string) map[string]string {
rules := map[string]string{"name": "required"}
if op == "create" {
rules["password"] = "required|between:8,255|confirmed"
} else {
rules["password"] = "nullable|between:8,255|confirmed"
}
return rules
}
```
- The form's `required` flags are still merged in, also for form-only fields.
- A rule on a form-only field is checked against the submitted value, or against nothing when the field was not sent; the model column of the same name is never read. `confirmed` compares with the submitted `<field>_confirmation`.
- Rule strings use the tokens `lagoon.Validate` supports. An unknown token is the opaque 500 on every save, so checks outside that set belong in a hook that returns a `cabana.ValidationError`.
- The model must still have a `Rules` method; relation forms and settings forms keep using the model's rules.
## Refusing a write
A hook or an action stops a write by returning an error. Which error decides what the administrator sees:

View File

@@ -95,15 +95,29 @@ for _, f := range form.Fields {
| `partial` | A server-rendered template; see [Partials and widgets](partials-and-widgets.md). |
| `fileupload` | Uploads for an attachOne or attachMany relation; see [File uploads](#file-uploads). |
| `datepicker` | A date, date and time, or time of day; see [Date pickers](#date-pickers). |
| `password` | A masked input with a show and hide button. It is a form-only field: the value is sent with a save and never returned; see [Form-only fields](#form-only-fields). |
The WinterCMS widgets that are not in this list (the rich editor, the markdown editor, the code editor, the color picker, the media finder, the repeater, the tag list and the others) are not provided. A field with one of those types stops the start-up.
### Field options
A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields. WinterCMS keys outside this set, such as `readOnly`, `disabled`, `trigger` or `dependsOn`, are refused.
A field takes `label`, `comment`, `type`, `required`, `default`, `tab`, `span` (`left`, `right`, `full`, `auto`, `row`), `size` (`tiny`, `small`, `large`, `huge`, `giant`), `context`, `attributes` (scalar HTML attributes for the input), `options` and `emptyOption`, plus `nameFrom` and `relation` on relation fields and `preset` on text fields. WinterCMS keys outside this set, such as `readOnly`, `disabled`, `trigger` or `dependsOn`, are refused.
`context: update` shows a field only on the update form, and `context: create` only on the create form; a list of contexts is also accepted, and `context: preview` shows a field only on the [preview screen](#preview-screen). The context is enforced on the server too: a field that is hidden on a form is never written by that form's save, whatever the request body holds.
`preset` makes a `text` field follow another text field of the same form while the administrator has not edited it, as a slug field follows a title. It is the source field's name, or a mapping with `field` and `type`:
```yaml
slug:
label: acme.blog::lang.posts.slug
type: text
preset:
field: title
type: slug
```
`type: slug` (the default, and what the short form `preset: title` means) lower-cases the text and turns every run of characters other than ASCII letters and digits into one hyphen; `type: exact` copies the text. The admin SPA applies it on the create form only, and the first manual edit of the field stops it. The server does not fill the field: a model that needs a slug even when none is sent sets it in its own `BeforeValidate`. The schema reports the key as `preset` (a `cabana.FieldPreset`). A `preset` on another field type, an unknown type, or a source that is not a text field of the same form stops the start-up, and the key is not accepted on settings forms or relation forms.
## Date pickers
A `type: datepicker` field edits one model column. Its `mode` decides the column's Go type, and the start-up stops when they do not match:
@@ -216,6 +230,26 @@ messages:
- `recordUrl` in `config_list.yaml` and the form's `create.redirect`, `update.redirectClose` and the other redirects may point at the screen as `<vendor>/<plugin>/<controller>/preview/:id`. On the update form of a record with a preview, the back arrow and Cancel return to the preview; after a delete the form goes to the list.
- The footer holds the record actions the show response offers in `meta.actions`, then the edit button. After an action the record and the status hint are loaded again in place.
## Form-only fields
Some fields of a form are not columns of the record: a password and its confirmation, or a "send an invitation" checkbox. A controller lists them through `pact.FormVirtualFields`:
```go src=modules/cabana/example_form_seams_test.go#MembersController.FormVirtualFields
// FormVirtualFields names the fields of fields.yaml that are not columns of
// the form. cabana never fills or returns them.
func (MembersController) FormVirtualFields() []string {
return []string{"password", "password_confirmation", "notify"}
}
```
- A listed field needs no model column. cabana never binds it, never fills it into the model and never puts it in a record response, on any route. A model column with the same name (a stored password hash) is not touched by the form.
- The values an administrator submits reach the controller's Form hooks through `cabana.VirtualFieldsFromContext(ctx)`; see [Admin controllers](admin-controllers.md#form-only-values-and-rules). Only fields that were sent and whose `context` allows the operation are there. A value must be a scalar: an object or a list is a 422 on the field.
- Every listed name must be a field of the form's `fields.yaml` with the type `password`, `text`, `textarea`, `number`, `checkbox`, `switch` or `dropdown`. Anything else stops the start-up.
- `type: password` is always a form-only field: a password field the controller does not list stops the start-up. The admin SPA shows it empty on every load, leaves an empty password out of an update (empty means unchanged), and clears it after a save. A confirmation is a second `password` field, compared by the `confirmed` rule on the server.
- Form-only fields are not available on settings forms or relation forms.
## What a save may write
The form's writable fields are bound to model columns at boot. A save passes only those fields that are also in the model's `Fillable` list, drops unknown keys, case variants and nested objects, and fills the model with `lagoon.Fill` (see [Models](../database/models.md)). The model's validation rules (a `Rules` method returning `lagoon.Validate` rule strings) and the form's `required` flags are checked in the save's transaction, and a failure is a 422 with messages per field. A value that does not fit its column is also a 422 on that field.
The form's writable fields are bound to model columns at boot. A save passes only those fields that are also in the model's `Fillable` list, drops unknown keys, case variants and nested objects, and fills the model with `lagoon.Fill` (see [Models](../database/models.md)). The model's validation rules (a `Rules` method returning `lagoon.Validate` rule strings) and the form's `required` flags are checked in the save's transaction, and a failure is a 422 with messages per field. A value that does not fit its column is also a 422 on that field. A controller implementing `pact.FormRules` supplies its own rule set per operation, which replaces the model's rules for admin saves.
[Form-only fields](#form-only-fields) are never written by cabana. Their submitted values are validated, when a rule names them, and handed to the controller's hooks; what is stored from them is the hook's decision.