Appearance
Forms, Validation & Actions
How Angular forms post data to PHP controllers, handle 422 field validation errors, display domain error toasts, and navigate to the next view without full page reloads.
The POST → JSON → navigate() pattern
In modern LIMS modules, POST actions return JSON (never HTTP redirects) and the Angular view drives the next step:
- Submit the form via
postForm()(orpostFields()for non-form actions like delete/archive). - On 2xx,
navigate()to the next URL and calltoastStore.success(...). - On 422 (DTO validation failure), flatten field messages with
fieldErrors(error)and render each under its input while preserving user input. - On 403 / 404 / 409 (
HttpException), displayerrorMessage(error)withtoastStore.error(...).
postForm() vs ajaxAction() vs fusionFormIntercept
| Approach | Sends | When to use |
|---|---|---|
postForm(url, form, extra?) / postFields(url, fields) | FormData ($_POST + $_FILES) with X-App-Request: true | Default choice for forms & mutations. Fields arrive in $_POST, so LimsRouter::plainText() decodes system.php HTML entities and converts empty strings to null (so required DTO fields fail properly and optional fields save as NULL). Supports file uploads natively. |
ajaxAction(action, data, { feature }) | JSON body (application/json) | Small JSON-only calls where raw strings should not be converted to null and no files are uploaded. Skips LimsRouter's $_POST normalization. |
<form fusionFormIntercept> | Form post expecting Fusion::render() | Actions whose controller answers directly with a rendered page instead of JSON (errors go into router.errors()). |
Standard postForm.ts helper
Copy this lightweight helper into your module's UI/Components/postForm.ts (see Notes/UI/Components/postForm.ts or QualityAssurance/UI/Components/postForm.ts):
ts
import { FusionRequestError } from "@labmin/fusion-angular";
export function postForm<T = unknown>(
url: string,
form: HTMLFormElement,
extra: Record<string, string> = {},
): Promise<T> {
const body = new FormData(form);
for (const [name, value] of Object.entries(extra)) {
body.set(name, value);
}
return send<T>(url, { method: "POST", body });
}
export function postFields<T = unknown>(
url: string,
fields: Record<string, string | number | readonly (string | number)[] | null | undefined>,
): Promise<T> {
const body = new FormData();
for (const [name, value] of Object.entries(fields)) {
if (Array.isArray(value)) {
for (const item of value) body.append(`${name}[]`, String(item));
} else if (value !== null && value !== undefined) {
body.append(name, String(value));
}
}
return send<T>(url, { method: "POST", body });
}
export function getJson<T = unknown>(url: string): Promise<T> {
return send<T>(url, { method: "GET" });
}
async function send<T>(url: string, init: RequestInit): Promise<T> {
const response = await fetch(url, {
...init,
headers: { "X-App-Request": "true", Accept: "application/json" },
});
const body = await response.json().catch(() => null);
if (!response.ok) throw new FusionRequestError(response.status, body);
return body as T;
}
export function fieldErrors(error: unknown): Record<string, string> {
if (!(error instanceof FusionRequestError) || error.status !== 422) return {};
const body = error.body as { errors?: unknown } | null;
const list = Object.values(body?.errors ?? {}).flat() as { path?: string; message: string }[];
const fields: Record<string, string> = {};
for (const { path, message } of list) {
if (!path) continue;
const field = path.includes(".") ? path.slice(path.indexOf(".") + 1) : path;
fields[field.replace(/\[\d+\]$/, "")] ??= message;
}
return fields;
}
export function errorMessage(error: unknown, fallback = "Something went wrong."): string {
if (error instanceof FusionRequestError) {
const body = error.body as { message?: unknown } | null;
return typeof body?.message === "string" ? body.message : fallback;
}
return error instanceof Error ? error.message : fallback;
}Reusable runStep() action helper
For pages with many workflow buttons (publish, archive, move, delete), wrap the repeated try/catch/busy/navigate/toast boilerplate in a runStep() helper:
ts
export async function runStep<T>(
busy: WritableSignal<boolean>,
send: () => Promise<T>,
next: string | ((answer: T) => string),
done: string,
errors?: WritableSignal<Record<string, string>>,
): Promise<boolean> {
busy.set(true);
errors?.set({});
try {
const answer = await send();
if (await navigate(typeof next === "string" ? next : next(answer))) {
toastStore.success(done);
}
return true;
} catch (error) {
const fields = fieldErrors(error);
if (errors && Object.keys(fields).length > 0) {
errors.set(fields);
} else {
toastStore.error(errorMessage(error, "The action could not be completed."));
}
return false;
} finally {
busy.set(false);
}
}Combining <fusion-select> / ngModel with postForm()
Native <input> and <textarea> elements are captured automatically by new FormData(form). For Angular-bound controls like <fusion-select [(ngModel)]="labId"> or <fusion-datepicker> that don't emit a native named form field, pass their signal values via postForm's third extra argument:
ts
await postForm<{ id: number }>(
url("save", { feature: "orders", query: { id: this.order()?.id ?? null } }),
event.target as HTMLFormElement,
{ labId: String(this.labId()) },
);Dynamic DTO validation (when DTO varies at runtime)
Normally, type-hinting OrderFormDTO $data on a #[Post] method triggers automatic router validation. When the DTO class depends on runtime input (such as a multi-stage workflow step), validate manually with Materialize::tryBuild() and return the exact same 422 shape:
php
$result = Materialize::tryBuild($request->post(), $dtoClass);
if (!$result->ok) {
return new JsonResponse(['errors' => ['data' => $result->errors]], 422);
}Destructive confirmations & resetting modal forms
- Reset dialog forms on open: Wrap dialog
<form>markup in@if (open()) { ... }so inputs reset cleanly each time the dialog opens. - Guard destructive confirmations: Always pass
defaultFocus: "reject"when callingConfirmationService.confirm(...)for delete or archive prompts so pressing Enter never triggers destruction.