With sealgen@0.14.14, you can now easily set the initial values for the fields in the form. This might be of interest to @FilipI and @ziomek, who have some form-related tasks.
To use that, add a getInitialValues
method to a form, like so:
async getInitialValues() {
return {
email: "some-email@hehe.com",
};
}
Now, when a form is visited with an empty HTTP POST body, it will use the default values.
Here’s a full form for reference:
import type { Context } from "koa";
import type { FormData } from "@sealcode/sealgen";
import { Form, Fields, Controls, fieldsToShape } from "@sealcode/sealgen";
import html from "../html.js";
import { Users } from "../collections/collections.js";
export const actionName = "SomeForm";
const fields = {
email: new Fields.CollectionField(true, Users.fields.email),
};
export const SomeFormShape = fieldsToShape(fields);
export default new (class SomeFormForm extends Form<typeof fields, void> {
defaultSuccessMessage = "Formularz wypełniony poprawnie";
fields = fields;
controls = [
new Controls.SimpleInput(fields.email, { label: "Email:", type: "email" }),
];
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async canAccess(_: Context) {
return { canAccess: true, message: "" };
}
async onSubmit() {
//noop
return;
}
async getInitialValues() {
return {
email: "some-email@hehe.com",
};
}
async render(ctx: Context, data: FormData, show_field_errors: boolean) {
return html(ctx, "SomeForm", await super.render(ctx, data, show_field_errors));
}
})();