Skip to content

Translating a form

The schema's own words - its title, labels, help, placeholders, affixes and the labels of its options - can travel with it in every language it is offered in. Translate(culture, texts) adds them in C#, x-translations carries them in JSON Schema, and an IBormSchemaLocalizer wraps the resource files an application already has.

Pick a language. By default a form follows the UI culture; this one is given its own with state.Language, which needs no culture data - this site runs with InvariantGlobalization, as many WebAssembly apps do - and marks the form with a lang a screen reader follows. A dialect without a table of its own, de-CH, reads its language's. The library's own words - "This field is required." and the buttons - follow the same language: this site registers AddBormTranslations(), which speaks twelve languages besides English, and an IBormMessageProvider of your own can replace it. Submit the empty form in each language to see the messages.

العربية shows the two layers apart: the schema carries no Arabic, so its labels stay as written, while the library's words - the button, the messages - are Arabic. It also ticks Right to left, which sets dir="rtl" on the container; the library sets no dir itself, and its layout uses logical CSS properties throughout, so it mirrors as the page does.
Live form
Language
Order

Tell us who the seats are for.

As it appears on the invoice.

Plan
View source
@page "/localization"

<button type="button" @onclick='() => _state.Language = "de"'>Deutsch</button>
<BormView State="_state" OnValidSubmit="HandleSubmit" />

@code {
    private readonly TeamOrder _model = new();
    private BormState _state = default!;

    protected override void OnInitialized()
    {
        var schema = BormBuilder.For<TeamOrder>()
            .Title("Order")
            .Description("Tell us who the seats are for.")
            .Field(x => x.Company, f => f.Required().Placeholder("Contoso Ltd").Help("As it appears on the invoice."))
            .Field(x => x.Plan, f => f.AsRadio()
                .Options(("solo", "Solo"), ("team", "Team"), ("enterprise", "Enterprise")))
            .Field(x => x.Seats, f => f.Range(1, 500).Suffix("users"))
            .Field(x => x.Notes, f => f.AsTextArea(3))
            // Keys: {field}.label / .help / .placeholder / .prefix / .suffix, {field}.options.{value},
            // steps.{id}.title, form.title and form.description.
            .Translate("de", new Dictionary<string, string>
            {
                ["form.title"] = "Bestellung",
                ["form.description"] = "Sagen Sie uns, für wen die Plätze sind.",
                ["Company.label"] = "Firma",
                ["Company.placeholder"] = "Contoso GmbH",
                ["Company.help"] = "So, wie sie auf der Rechnung steht.",
                ["Plan.label"] = "Tarif",
                ["Plan.options.solo"] = "Einzelplatz",
                ["Plan.options.enterprise"] = "Unternehmen",
                ["Seats.label"] = "Plätze",
                ["Seats.suffix"] = "Nutzer",
                ["Notes.label"] = "Anmerkungen",
            })
            .Translate("fr", new Dictionary<string, string> { /* ... */ })
            .Build();

        // Null follows CultureInfo.CurrentUICulture; a name gives this form a language of its own.
        _state = new BormState(schema, new BormModelDataAccessor(_model));
    }

    public void Dispose() => _state.Dispose();
}

Two kinds of text, two ways to translate them

TextWhoseTranslated by
Labels, help, placeholders, prefixes and suffixes, option labels, step titles, the form's title The schema's Translate(culture, texts) in C#, x-translations in JSON Schema, or an IBormSchemaLocalizer over your resource files
Validation messages, the buttons, the error summary, announcements, the designer The library's AddBormTranslations() for twelve languages, or an IBormMessageProvider of your own

A schema text is found under its key: {field}.label, .help, .placeholder, .prefix, .suffix, {field}.options.{value}, steps.{id}.title, steps.{id}.description, form.title and form.description. {field} is the field's path with the rows taken out (Lines.Product for every line's product), or the key a field names itself with x-i18n. A text the tables do not have is shown as written - as the plan "Team" is in German here. A message passed to a rule, or a label passed to BormView, is used as it is in every language.

Over the resource files you already have

Both layers can wrap IStringLocalizer. Return null from a schema localizer to keep the text as written, and fall back to BormDefaultMessageProvider for a key your resources do not cover - the keys are listed on BormMessageKeys.

// Program.cs
builder.Services.AddBormSchemaLocalizer<FormText>();
builder.Services.AddBormMessages<MyMessages>();          // instead of AddBormTranslations()

public sealed class FormText(IStringLocalizer<FormText> localizer) : IBormSchemaLocalizer
{
    public string? Localize(string key, string? text)
        => localizer[key] is { ResourceNotFound: false } found ? found.Value : null;
}

public sealed class MyMessages(IStringLocalizer<MyMessages> localizer) : IBormMessageProvider
{
    public string Get(string key, params object?[] args)
        => localizer[key, args] is { ResourceNotFound: false } found
            ? found.Value
            : BormDefaultMessageProvider.Instance.Get(key, args);
}

A provider that should answer in each form's own Language implements IBormLocalizedMessageProvider, whose Get(language, key, args) the form calls. BormValidator.Language does the same for a form judged on its own on the server, and BormDesigner takes a Language parameter. Dates and numbers in a review follow CurrentCulture; the date and number inputs themselves are the browser's, in the user's own locale.

An unhandled error has occurred. Reload 🗙