Setting initial values of a sealgen form

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.

image

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));
	}
})();

1 Like

Do we get ctx argument inside of this method? Cause we will have to fetch the data firs

yep! mountable-with-fields.ts · sealgen

Is there a way to have an initial value for photo too?

I have this control
image

And I dont think item.get("photoForMetadata") is compatibale with that. And I have to do that since file field is required. I wanted to make it optional for edit page and only update the photo if there is something selected but changing required to false throws an error

image

It is! I’ve described it in detail here:

Sorry for the late response - I’ve decided to straighten some messy code that deals with files and forms. It’s much cleaner now.

And… now item.get("field_name") returns a proper type instead of unknown :heart:

1 Like