Skip to content

DynamicForm

Renders a form that is plain data, a DynamicFormSchema of DynamicFieldSchema, for the cases where the fields are not known when you compile, such as a form stored as JSON. Values are keyed by field name and the output is a dictionary.

On this page

Examples

Form from a schema

A field is a DynamicFieldSchema with a Key, a Kind and its rules. Keep the schema in a static field, because the component creates a new controller whenever it receives a different schema instance. OnSubmit receives the same dictionary as BuildOutput().

Contact us

Razor
@using Klyroo.Form.Dynamic

<div class="flex w-full max-w-lg flex-col gap-4">
    <KlyDynamicFormEngine Schema="Schema" SubmitLabel="Send" OnSubmit="Send" />
    @if (_sent is not null)
    {
        <p class="m-0 text-sm text-(--klyroo-text-muted)">Thanks, we will write to @_sent.</p>
    }
</div>

@code {
    private string? _sent;

    // The form is plain data and its values are keyed by field name. Keep the schema in a static field: a new instance starts a new controller.
    private static readonly DynamicFormSchema Schema = new()
    {
        FormKey = "contact",
        Title = "Contact us",
        Fields =
        [
            new DynamicFieldSchema { Key = "name", Label = "Name", Required = true },
            new DynamicFieldSchema
            {
                Key = "email", Label = "Email", Required = true,
                Validators = [new DynamicValidatorRule("email", "Enter a valid email address", (value, _) => value?.ToString()?.Contains('@') == true)],
            },
            new DynamicFieldSchema
            {
                Key = "topic", Label = "Topic", Kind = FormFieldKind.Select,
                Options = [new("sales", "Sales"), new("support", "Support")],
            },
            new DynamicFieldSchema { Key = "message", Label = "Message", Kind = FormFieldKind.Textarea, Required = true },
        ],
    };

    // The output holds the fields in effect, by key.
    private Task Send(IReadOnlyDictionary<string, object?> data)
    {
        _sent = (string?)data["email"];
        return Task.CompletedTask;
    }
}

Conditions and rows

A field whose Condition returns false is not drawn, is skipped by validation and is left out of the output, but its value stays in the state. RequiredWhen is evaluated on each validation, TransformOutput changes the value only in the output, and an ArrayTable field holds one dictionary per row.

Billing

Lines

No items yet

Razor
@using Klyroo.Form.Dynamic

<div class="w-full max-w-2xl">
    <KlyDynamicFormEngine Schema="Schema" SubmitLabel="Save" />
</div>

@code {
    private static readonly DynamicFormSchema Schema = new()
    {
        FormKey = "billing",
        Title = "Billing",
        Fields =
        [
            new DynamicFieldSchema
            {
                Key = "accountType", Label = "Account type", Kind = FormFieldKind.Select, DefaultValue = "personal",
                Options = [new("personal", "Personal"), new("business", "Business")],
            },
            // A field whose Condition is false is not drawn, not validated and left out of the output.
            new DynamicFieldSchema
            {
                Key = "company", Label = "Company", Required = true,
                Condition = form => form.GetValue<string>("accountType") == "business",
            },
            new DynamicFieldSchema { Key = "country", Label = "Country", DefaultValue = "FR" },
            new DynamicFieldSchema
            {
                Key = "vat", Label = "VAT number",
                Condition = form => form.GetValue<string>("accountType") == "business",
                RequiredWhen = form => form.GetValue<string>("country") != "US",
                TransformOutput = value => value?.ToString()?.Replace(" ", "").ToUpperInvariant(),
            },
            new DynamicFieldSchema
            {
                Key = "lines", Label = "Lines", Kind = FormFieldKind.ArrayTable, Required = true, AddItemLabel = "Add line",
                Fields =
                [
                    new DynamicFieldSchema { Key = "sku", Label = "SKU", Required = true, MaxLength = 12 },
                    new DynamicFieldSchema { Key = "qty", Label = "Quantity", Kind = FormFieldKind.Number, Min = 1, DefaultValue = 1.0 },
                ],
            },
        ],
    };
}

Steps

Steps replaces Fields. The controller validates only the current step when the user presses Next, then runs OnBeforeNext with the index of the step being left. A step with SkipWhen returning true is passed over in both directions, and the last step shows the submit button.

Create your workspace

  1. 1. Workspace
  2. 3. Invite
Plan
Razor
@using Klyroo.Form.Dynamic

<div class="w-full max-w-lg">
    <KlyDynamicFormEngine Schema="Schema" SubmitLabel="Finish" />
</div>

@code {
    private static readonly DynamicFormSchema Schema = new()
    {
        FormKey = "onboarding",
        Title = "Create your workspace",
        // Runs when the user leaves a step with Next, with the index of that step.
        OnBeforeNext = async (form, stepIndex) =>
        {
            if (stepIndex != 0) return true;
            var taken = form.GetValue<string>("slug") == "acme";
            if (taken) form.SetError("slug", "This address is taken", blocking: true);
            return !taken;
        },
        Steps =
        [
            new DynamicStepSchema
            {
                Key = "workspace", Title = "Workspace",
                Fields =
                [
                    new DynamicFieldSchema { Key = "slug", Label = "Address", Required = true },
                    new DynamicFieldSchema
                    {
                        Key = "plan", Label = "Plan", Kind = FormFieldKind.Radio, DefaultValue = "free",
                        Options = [new("free", "Free"), new("team", "Team")],
                    },
                ],
            },
            new DynamicStepSchema
            {
                Key = "billing", Title = "Billing",
                SkipWhen = form => form.GetValue<string>("plan") == "free",
                Fields = [new DynamicFieldSchema { Key = "vat", Label = "VAT number", Required = true }],
            },
            new DynamicStepSchema
            {
                Key = "invite", Title = "Invite",
                Fields = [new DynamicFieldSchema { Key = "emails", Label = "Teammates", Kind = FormFieldKind.Textarea }],
            },
        ],
    };
}

API

KlyDynamicFormEngine

Renders a DynamicFormSchema as a form: header, optional stepper with the description of the current step, a field grid of Columns columns and the footer actions (Back, Reset, Cancel, Next, Submit). Pass either a DynamicFormController through Form or a schema through Schema . The component subscribes to Changed and re-renders on every change.

Parameters

Name Type Default Description
Class string Classes added to the root element, merged last so they win over the theme.
FieldTemplates IReadOnlyDictionary<string, RenderFragment<DynamicControlContext>> Renderers of the Custom fields by CustomKey , each a RenderFragment<DynamicControlContext> that draws the control. They win over the ones registered with DynamicControlContext}) .
Form DynamicFormController The controller to render. Use it when you need to read or change the form from code. Takes precedence over Schema .
Input IReadOnlyDictionary<string, object> Initial values by field key for the controller created from Schema . Ignored when Form is set.
OnSave Func<IReadOnlyDictionary<string, object>, CancellationToken, Task<bool>> Your save step: called with BuildOutput after validation and the schema hooks passed, 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 user's edits dirty and the form open, after reporting the reason with Boolean) or Boolean) . The token is cancelled when the component is disposed. It runs through CancellationToken) .
Schema DynamicFormSchema 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.Inline 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<IReadOnlyDictionary<string, object>> Called with the current output when the user presses Cancel or the close button. When bound, the Cancel button is shown.
OnSubmit EventCallback<IReadOnlyDictionary<string, object>> Called with BuildOutput 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 .