Skip to content

Custom renderer

Every control is drawn by a component looked up in a registry, and the registry is yours to add to. The rating field below is a star-rating component registered under the key "rating" and asked for with CustomRenderer("rating"). Only the drawing changes: the value, its rule, the label, the error message, focus after a failed submit and the error summary all work exactly as they do for a built-in control.

Submit without a rating: the field's own Must rule refuses it, and focus lands on the first star. The stars are a radio group, so the arrow keys choose and Tab leaves - try it from the keyboard. Pick a rating and the message goes the moment the value is written.
Live form
Leave feedback

View source
@page "/custom-renderer"

<BormView Definition="_schema" Data="_data" OnValidSubmit="HandleSubmit" SubmitText="Send feedback" />

@code {
    private BormDefinition _schema = default!;
    private readonly Dictionary<string, object?> _data = new();

    protected override void OnInitialized()
    {
        _schema = BormBuilder.Create()
            .Title("Leave feedback")
            .Field("rating", BormFieldType.Custom, f => f
                .Label("How would you rate us?")
                .CustomRenderer("rating")
                .Attr("max", 5)
                .Must(v => v is int i && i >= 1, "Please pick a rating."))
            .Text("comment", f => f.AsTextArea(3).Label("Comments").Placeholder("Optional"))
            .Build();
    }

    private void HandleSubmit(BormState state)
    {
        var json = System.Text.Json.JsonSerializer.Serialize(_data,
            new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
    }
}

// Program.cs - the renderer is registered against the key the field asks for:
//   builder.Services.AddBorm(registry => registry.RegisterCustom<StarRatingInput>("rating"));

@* Renderers/StarRatingInput.razor - the essentials. Each star is a real radio button (hidden from sight,
   not from the keyboard), so the group is one tab stop and the arrow keys choose, as in any radio group. *@
@inherits BormInputBase

<div id="@Context.ElementId" role="radiogroup" @ref="Element" tabindex="-1"
     aria-labelledby="@(Field.ShowLabel ? Context.LabelId : null)" aria-label="@AriaLabel"
     aria-required="@AriaRequired" aria-invalid="@AriaInvalid" aria-describedby="@DescribedBy">
    @for (var n = 1; n <= Max; n++)
    {
        var star = n;
        <label class="star @(star <= Current ? "star--on" : "")">
            <input type="radio" name="@_group" value="@star" checked="@(star == Current)"
                   disabled="@DisabledOrReadOnly" @onchange="@(() => Context.SetValueAsync(star))" />
            <span aria-hidden="true">@(star <= Current ? "★" : "☆")</span>
            <span class="star__name">@(star == 1 ? "1 star" : $"{star} stars")</span>
        </label>
    }
</div>

@code {
    private readonly string _group = "star-rating-" + Guid.NewGuid().ToString("N");

    // .Attr("max", 5) on the field arrives in Field.Attributes.
    private int Max => Field.Attributes.TryGetValue("max", out var m) && m is int i ? i : 5;
    private int Current => Context.Value is int v ? v : 0;
}

What a renderer is handed

A renderer inherits BormInputBase. It never reads or writes the model itself: it reads the field's value from its context and writes through it, so conditions, computed values, dirty tracking and validation all see the change.

MemberWhat it is for
FieldThe field's definition: its label, options, rules and the Attributes the schema gave it (Attr("max", 5) arrives here).
Context.Value, Context.StringValueThe current value, as it is and as text.
Context.SetValueAsync(value)Writes a typed value. Context.SetFromStringAsync(text) converts text the way the built-in boxes do, and reports what the model cannot hold.
Context.ElementId, Context.LabelIdThe ids the label and the error summary point at, so put ElementId on your control.
AriaRequired, AriaInvalid, DescribedBy, AriaLabelThe accessibility wiring, ready to put on the control: required, invalid once the user should see it, the help and message ids, and a name when the label is hidden.
Disabled, ReadOnly, DisabledOrReadOnlyWhether a condition, the form or a containing group has locked the field.
CssClassThe built-in controls' class, with --invalid when the field shows an error.
Element, FocusAsync()What "go to the first error" and the summary's links focus. Override FocusAsync when the element to focus is inside another component.

Registering it - or replacing a built-in control

AddBorm takes a callback that configures the registry. RegisterCustom adds a control under a key a field asks for by name; Register replaces the control drawn for a whole field type, everywhere - a date picker from your component library for every Date field, say. Calling AddBorm again configures the same registry, so a module can add its renderers after the application has added its own.

builder.Services.AddBorm(registry => registry
    .RegisterCustom<StarRatingInput>("rating")        // asked for with f.CustomRenderer("rating")
    .Register<MyDatePicker>(BormFieldType.Date));      // every Date field, without asking

A field that asks for a key nobody registered throws with a message naming the key, rather than quietly falling back to a text box. In JSON Schema the key travels as "x-renderer": "rating". To use Blazor's own InputText or a component library's inputs inside a renderer, see Blazor's own inputs.

An unhandled error has occurred. Reload 🗙