FormEngine
On this page
Renders a form declared from a C# model with FormSchema.For<TModel>: fields, rules, conditions, repeatable rows and steps, with a header, a stepper and the footer actions. A schema is stateless and kept in a static field, because a new schema instance makes the component start a new controller and drop what was typed.
Examples
Form from a C# model
Razor infers TModel from Schema and Model, but a method group given to OnSubmit stops the inference, so the example writes TModel. OnSave runs after validation while the form shows its saving state and returns true when the save worked; OnSubmit is raised afterwards with the same model. A submit writes the values into Model all or nothing. Statically rendered the form appears but does not react to input.
<div class="flex w-full max-w-lg flex-col gap-4">
<KlyFormEngine TModel="Contact" Schema="Schema" Model="_contact" SubmitLabel="Send" OnSave="SaveAsync" OnSubmit="Sent" />
@if (_sentTo is not null)
{
<p class="m-0 text-sm text-(--klyroo-text-muted)">Thanks, we will write to @_sentTo.</p>
}
</div>
@code {
private readonly Contact _contact = new();
private string? _sentTo;
// A static field: a new schema instance makes the component start a new controller and drop what was typed.
private static readonly FormSchema<Contact> Schema = FormSchema.For<Contact>(s =>
{
s.FormKey = "contact";
s.Title = "Contact us";
s.Field(c => c.Name, f => f.Label("Your name").Required());
s.Field(c => c.Email, f => f.Label("Email").Required().Rule(e => e.Contains('@'), "Enter a valid email address"));
s.Field(c => c.Topic, f => f.AsRadio());
s.Field(c => c.Message, f => f.AsTextarea().Required().MaxLength(500));
});
// Runs after validation, while the form shows its saving state. Return false to keep the edits and the form open.
private Task<bool> SaveAsync(Contact contact, CancellationToken cancellationToken) => Task.FromResult(true);
private void Sent(Contact contact) => _sentTo = contact.Email;
public enum Topic { Sales, Support, Press }
public sealed class Contact
{
public string Name { get; set; } = "";
public string Email { get; set; } = "";
public Topic Topic { get; set; }
public string Message { get; set; } = "";
}
}Conditions and repeatable rows
VisibleWhen shows the gift message only while the switch is on, and the handle of the switch is captured in a local. List declares the rows, and Required on the list asks for at least one.
<div class="w-full max-w-2xl">
<KlyFormEngine Schema="Schema" Model="_order" SubmitLabel="Place order" />
</div>
@code {
private readonly Order _order = new();
private static readonly FormSchema<Order> Schema = FormSchema.For<Order>(s =>
{
s.FormKey = "order";
s.Title = "New order";
s.Field(m => m.Customer, f => f.Label("Customer").Required());
var gift = s.Field(m => m.Gift, f => f.Label("This is a gift").AsSwitch());
// Shown only while the switch is on, and left out of the validation while hidden.
s.Field(m => m.GiftMessage, f => f.Label("Gift message").AsTextarea().VisibleWhen(c => c.Get(gift)).DependsOn(gift));
s.List(m => m.Lines, row =>
{
row.Field(l => l.Sku, f => f.Label("SKU").Required().MaxLength(12));
row.Field(l => l.Qty, f => f.Label("Quantity").Range(1, 99));
row.Field(l => l.Price, f => f.Label("Unit price").Rule(p => p > 0, "The price must be above zero"));
}, addLabel: "Add line", configure: f => f.Required());
});
public sealed class Order
{
public string Customer { get; set; } = "";
public bool Gift { get; set; }
public string GiftMessage { get; set; } = "";
public List<OrderLine> Lines { get; set; } = [];
}
public sealed class OrderLine
{
public string Sku { get; set; } = "";
public int Qty { get; set; } = 1;
public decimal Price { get; set; }
}
}Steps
Each step declares its fields and the controller validates only the current step when the user presses Next. A step with skipWhen is passed over in both directions, so a field in it can be Required without asking users who never see it.
<div class="w-full max-w-lg">
<KlyFormEngine TModel="Signup" Schema="Schema" SubmitLabel="Create account" OnSubmit="Created" />
@if (_created is not null)
{
<p class="m-0 mt-3 text-sm text-(--klyroo-text-muted)">Account created for @_created.</p>
}
</div>
@code {
private string? _created;
private void Created(Signup signup) => _created = signup.Email;
private static readonly FormSchema<Signup> Schema = Build();
private static FormSchema<Signup> Build()
{
FormField<Signup, PlanTier> plan = null!;
return FormSchema.For<Signup>(s =>
{
s.FormKey = "signup";
s.Title = "Create your account";
s.Step("account", "Account", step =>
{
step.Field(m => m.Email, f => f.Label("Email").Required().Rule(v => v.Contains('@'), "Enter a valid email address"));
step.Field(m => m.Password, f => f.AsPassword().Required().Rule(v => v.Length >= 8, "Use at least 8 characters"));
});
s.Step("plan", "Plan", step => plan = step.Field(m => m.Plan, f => f.AsRadio()));
// Passed over, in both directions, while the Free plan is chosen: its field is not required of that user.
s.Step("billing", "Billing", step =>
{
step.Field(m => m.VatNumber, f => f.Label("VAT number").Required());
}, skipWhen: c => c.Get(plan) == PlanTier.Free);
});
}
public enum PlanTier { Free, Team }
public sealed class Signup
{
public string Email { get; set; } = "";
public string Password { get; set; } = "";
public PlanTier Plan { get; set; }
public string VatNumber { get; set; } = "";
}
}Controller
With Form the controller is yours: the page reads IsDirty and HasBlockingErrors from it and re-renders on its Changed event. Model is then only the target of a submit.
Changed: no · Blocking errors: no
@implements IDisposable
<div class="flex w-full max-w-lg flex-col gap-4">
<KlyFormEngine TModel="Profile" Form="_form" Model="_profile" SubmitLabel="Save" ShowReset="false" />
<p class="m-0 text-sm text-(--klyroo-text-muted)">
Changed: @(_form.IsDirty ? "yes" : "no") · Blocking errors: @(_form.HasBlockingErrors ? "yes" : "no")
</p>
</div>
@code {
private readonly Profile _profile = new() { Name = "Ada Lovelace", Email = "ada@example.com" };
private FormController<Profile> _form = default!;
private static readonly FormSchema<Profile> Schema = FormSchema.For<Profile>(s =>
{
s.FormKey = "profile";
s.Title = "Your profile";
s.Field(m => m.Name, f => f.Required());
s.Field(m => m.Email, f => f.Required().Rule(v => v.Contains('@'), "Enter a valid email address"));
});
protected override void OnInitialized()
{
// With Form the controller is yours: read it from code, and re-render when it changes.
_form = new FormController<Profile>(Schema, _profile);
_form.Changed += OnChanged;
}
private void OnChanged() => InvokeAsync(StateHasChanged);
public void Dispose() => _form.Changed -= OnChanged;
public sealed class Profile
{
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
}API
KlyFormEngine<TModel>
Renders a FormSchema1 as a form: header, optional stepper with the description of the current step, a field grid of columns and the footer actions (Back, Reset, Cancel, Next, Submit). Pass either a Form1 through Form or a schema through Schema , with the Model to edit. is inferred from Form , Schema or Model . The component subscribes to Changed and re-renders on every change, and it gives the controller to the components inside it ( KlyFieldTemplate , KlyFormFieldView ).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
Class |
string |
Classes added to the root element, merged last so they win over the theme. | |
Form |
FormController |
The controller to render. Use it when you need to read or change the form from code. Takes precedence over Schema . | |
Model |
TModel |
The model to edit. Its values are the form's starting values, and a submit writes the values back into it (all or nothing, put back when a step fails), so members the form does not show keep their value. Without a model every submit creates a new . A different instance reloads the form, dropping unsaved edits. It is only read by the controller the component creates: with Form , it is only the target of a submit. | |
OnSave |
Func |
Your save step: called with the model after validation and the schema hooks passed (the Model with the values written into it, or a new one), while the form is still submitting (the button shows its saving state, a second submit is refused, Cancel is disabled). Return true when the save succeeded; the form is then clean and OnSubmit is raised. Return false to keep the edits dirty and the form open, after reporting the reason with Boolean) or Boolean) ; the model gets its previous values back. The token is cancelled when the component is disposed. It runs through CancellationToken) . | |
Schema |
FormSchema |
The schema to render when no Form is given. The component creates and owns the controller, and creates a new one when the schema instance changes. | |
Shell |
FormShellMode |
FormShellMode. |
How the form is presented. Anything other than Inline adds a close button to the header when OnCancel is bound. Values: Inline, Modal, Drawer, Fullscreen. |
ShowReset |
bool |
true |
Shows a reset button in the footer while the form is dirty. The default is true . |
SubmitLabel |
string |
Text of the submit button. The default is the Submit text of the current locale ( Submit ). |
Events
| Name | Type | Description |
|---|---|---|
OnCancel |
EventCallback |
Called when the user presses Cancel or the close button. When bound, the Cancel button is shown. |
OnSubmit |
EventCallback |
Called with the model after the form is submitted successfully, that is after validation, the schema hooks and OnSave passed. At that point the submission is over: IsSubmitting is false and the form is clean. Do the save itself in OnSave . |
Slots
| Name | Type | Description |
|---|---|---|
ChildContent |
RenderFragment |
Templates of the fields ( KlyFieldTemplate ). They draw nothing themselves: they hand their control to the field they name. |