Skip to content

DynamicFormPage

The page layout of a runtime form (KlyDynamicFormPage), a sidebar with the status of each section and one card per section, and KlyDynamicFieldView, which draws one field of a DynamicFormController by key where you want it.

On this page

Examples

Settings page with sections

A schema declares exactly one of Steps, Sections or Fields: with sections the fields are ignored. The page takes a controller through Form because it needs it to work out the state of each section, and it is a form element, so pressing Enter submits it.

Workspace settings

1 left to complete.

General

Notes

Razor
@using Klyroo.Form.Dynamic

<div class="w-full max-w-4xl">
    <KlyDynamicFormPage Form="_form" OnSubmit="Saved" />
    @if (_saved)
    {
        <p class="m-0 mt-3 text-sm text-(--klyroo-text-muted)">Settings saved.</p>
    }
</div>

@code {
    private bool _saved;

    // The page takes a controller, because it needs it to work out the state of each section.
    private readonly DynamicFormController _form = new(new DynamicFormSchema
    {
        FormKey = "settings",
        Title = "Workspace settings",
        Sections =
        [
            new DynamicSectionSchema
            {
                Key = "general", Label = "General",
                Fields =
                [
                    new DynamicFieldSchema { Key = "name", Label = "Workspace name", Required = true },
                    new DynamicFieldSchema { Key = "domain", Label = "Domain", Required = true },
                ],
            },
            new DynamicSectionSchema
            {
                Key = "notes", Label = "Notes", Optional = true,
                Fields = [new DynamicFieldSchema { Key = "description", Label = "Description" }],
            },
        ],
    });

    private void Saved(IReadOnlyDictionary<string, object?> data) => _saved = true;
}

Your own layout

KlyDynamicFieldView names a field by Key (or by Field) and renders nothing when the field is not shown. It does not subscribe to the controller, so the page re-renders on Changed.

Razor
@using Klyroo.Form.Dynamic
@implements IDisposable

@* The form component is not used: this page owns the controller, places each field by its key and re-renders when the controller changes. *@
<div class="flex w-full max-w-2xl flex-col gap-4">
    <div class="grid gap-4 sm:grid-cols-2">
        <KlyDynamicFieldView Form="_form" Key="name" />
        <KlyDynamicFieldView Form="_form" Key="email" />
    </div>
    <KlyDynamicFieldView Form="_form" Key="message" />
    <div class="flex items-center gap-3">
        <KlyButton Label="Send" OnClick="SendAsync" />
        <span class="text-sm text-(--klyroo-text-muted)">@_status</span>
    </div>
</div>

@code {
    private readonly DynamicFormController _form = new(new DynamicFormSchema
    {
        FormKey = "message",
        Fields =
        [
            new DynamicFieldSchema { Key = "name", Label = "Name", Required = true },
            new DynamicFieldSchema { Key = "email", Label = "Email", Required = true },
            new DynamicFieldSchema { Key = "message", Label = "Message", Kind = FormFieldKind.Textarea, Required = true },
        ],
    });

    private string _status = "";

    protected override void OnInitialized() => _form.Changed += OnChanged;

    private void OnChanged() => InvokeAsync(StateHasChanged);

    private async Task SendAsync() => _status = await _form.SubmitAsync() ? "Sent" : "Fix the errors above";

    public void Dispose() => _form.Changed -= OnChanged;
}

Custom control

A field of kind Custom draws the control that the dictionary FieldTemplates holds under its CustomKey, a RenderFragment of DynamicControlContext. FieldTemplates takes precedence over the renderers registered for the whole app, and a Custom field with no renderer shows a notice instead of a control.

Feedback

1 left to complete.

Rating

Razor
@using Klyroo.Form.Dynamic

<div class="w-full max-w-4xl">
    <KlyDynamicFormPage Form="_form" FieldTemplates="_templates" />
</div>

@code {
    private readonly DynamicFormController _form = new(new DynamicFormSchema
    {
        FormKey = "feedback",
        Title = "Feedback",
        Sections =
        [
            new DynamicSectionSchema
            {
                Key = "rating", Label = "Rating",
                Fields =
                [
                    // A Custom field draws the control the schema's CustomKey names in FieldTemplates.
                    new DynamicFieldSchema { Key = "rating", Label = "How was it?", Kind = FormFieldKind.Custom, CustomKey = "stars", Required = true },
                    new DynamicFieldSchema { Key = "comment", Label = "Comment", Kind = FormFieldKind.Textarea },
                ],
            },
        ],
    });

    private IReadOnlyDictionary<string, RenderFragment<DynamicControlContext>> _templates = default!;

    protected override void OnInitialized() => _templates = new Dictionary<string, RenderFragment<DynamicControlContext>> { ["stars"] = Stars };

    private RenderFragment<DynamicControlContext> Stars => context =>
        @<div id="@context.Id" role="radiogroup" aria-labelledby="@context.LabelledBy" aria-describedby="@context.DescribedBy"
              aria-invalid="@(context.Error is null ? null : "true")" class="flex gap-1">
            @for (var star = 1; star <= 5; star++)
            {
                var value = star;
                <button type="button" disabled="@context.Disabled" aria-pressed="@(context.Current<int>() >= value ? "true" : "false")" aria-label="@($"{value} out of 5")"
                        class="cursor-pointer border-0 bg-transparent p-0 text-2xl @(context.Current<int>() >= value ? "text-(--klyroo-primary)" : "text-(--klyroo-text-muted)")"
                        @onclick="@(() => context.Commit(value))" @onblur="context.Blur">★</button>
            }
        </div>;
}

API

KlyDynamicFormPage

Renders a sectioned form as a page: a sidebar listing each section with its completion status, and one card per section laid out by Span . Fields render with the same controls, labels, containers and repeatable lists as KlyDynamicFormEngine , and the page is a form element, so pressing Enter in a field submits it.

Parameters

Name Type 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. Its schema must declare Sections .
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. Return true when the save succeeded; the form is then clean and OnSubmit is raised. Return false to keep the edits dirty, after reporting the reason with Boolean) or Boolean) . The token is cancelled when the component is disposed.

Events

Name Type Description
OnSubmit EventCallback<IReadOnlyDictionary<string, object>> Called with BuildOutput after the form is submitted successfully, that is after validation, the schema hooks and OnSave passed. The submission is over at that point and the form is clean.

KlyDynamicFieldView

Renders one field of a DynamicFormController with the control of its FormFieldKind , its label, description, hint, help, error and per-field reset, the way KlyDynamicFormEngine and KlyDynamicFormPage render their fields. Containers, tabs and repeatable lists render their children too. Place it in a CSS grid of Columns columns, since the field sets its own grid-column span. It renders nothing when DynamicFieldSchema) is false . It does not subscribe to Changed : render it from a component that re-renders on that event, so changes made elsewhere (by code or by another field) show up.

Parameters

Name Type Description
Class string Classes added to the root element, merged last so they win over the theme.
Field DynamicFieldSchema The field to render, usually one of CurrentVisibleTopFields . Containers render their children too.
FieldTemplates IReadOnlyDictionary<string, RenderFragment<DynamicControlContext>> Renderers of the Custom fields by CustomKey . They win over the ones registered with DynamicControlContext}) , and reach the fields inside containers, tabs and lists.
Form (required) DynamicFormController The controller that holds the value of the field.
Key string The key of the field to render, as an alternative to Field : the field of Form with this key. Field wins when both are set. Nothing renders when the form has no field with this key.