EditForm

Learn how to create a EditForm

Getting Started with EditForm in BlazorForKids

The EditForm component in BlazorForKids allows you to create and update entity data using a simple, clean form interface — without writing repetitive form logic yourself. It handles form layout, validation, data loading, and saving automatically based on your model configuration.

The easiest way to generate an edit form is with just one line of code in the ComponentsDesigner section of your layout:

publicclassProgram

{

    publicstaticvoidMain(string[]args)

    {

        builder.CreateEditForm<EmployeeModel,Employee>("EmployeeEditForm");

    }

}

This tells the framework to create an edit form named EmployeeEditForm for managing the Employee entity using the EmployeeModel (the model used for editing) and Employee (the entity type).

How the EditForm Works

Every generated EditForm expects a parameter called ItemKey. This parameter tells the form whether it should create a new entity or edit an existing one:

  • If ItemKey is not set or is empty, the form assumes you are creating a new record.
  • If ItemKey has a valid value, the framework will retrieve the entity from the database and fill the form fields with its data — enabling you to edit it.

Displaying the EditForm on a Page

publicpartialclassHomeLayout:IBkApplicationLayout

{

    [SupplyParameterFromQuery(Name="EmployeeId")]

    publicstring?EmployeeIdParameter{get;set;}

    privateEmployeeIdEmployeeId=>EmployeeId.ParseOrEmpty(EmployeeIdParameter);

    publicvoidLayoutDesigner(IBkLayoutBuilderbuilder)

    {

    }

    publicvoidPagesDesigner(IBkPageBuilderbuilder)

    {

        builder.CreatePage("EmployeeEditFormPage",page=>

        {

            page.PageLink.Text("Edit Employee");

            page.PageLink.Description("Edit Employee");

            page.PageLink.Icon(Icons.PEN);

            page.Content(content=>

            {

// Option 1: Display the form in "Create" mode// If you add the EditForm component without setting the ItemKey parameter,// the framework will treat this as a request to create a new entity.                content.DisplayComponent<EmployeeEditForm>();

// Option 2: Display the form in "Edit" mode// To load an existing entity, pass its key to the EditForm using SetParameter.// The key value typically comes from the query string and is parsed beforehand.// The framework will use this key to fetch the entity from the database// and populate the form with existing values.                content.DisplayComponent<EmployeeEditForm>(component=>

                {

                    component.SetParameter(a=>a.ItemKey,EmployeeId);

                });

            });

        });

    }

    publicvoidComponentsDesigner(IBkComponentsBuilderbuilder)

    {

        builder.CreateEditForm<EmployeeModel,Employee>("EmployeeEditForm");

    }

}

Once the EditForm component is created, you can display it inside a page using the DisplayComponent method. There are two ways to do this:

1. Creating a New Entity

If you want to show a blank form for adding a new record, you simply include the form without passing any parameters:

publicclassProgram

{

    publicstaticvoidMain(string[]args)

    {

        content.DisplayComponent<EmployeeEditForm>();

    }

}

2. Editing an Existing Entity

If you want to load an existing entity into the form for editing, you’ll need to pass the ItemKey parameter. This is typically done by capturing an ID from the query string and converting it to the appropriate type.

Here’s how that works inside your layout:

        [SupplyParameterFromQuery(Name = "EmployeeId")]
public string? EmployeeIdParameter {get;set;}
private EmployeeId EmployeeId => EmployeeId.ParseOrEmpty(EmployeeIdParameter);

content.DisplayComponent<EmployeeEditForm>(component =>
{
component.SetParameter(a => a.ItemKey, EmployeeId);
});

By passing the parsed EmployeeId to the form, the framework will attempt to load the employee with that ID from the database. If the record is found, the form is pre-filled and ready for editing. If not, the framework will treat it as a "create new" form.

Recommended Approach

Even though there are two display options, you can always use the second method — passing the ItemKey. If you pass an empty or null key, the form will behave like a creation form. This makes your logic simpler and more uniform across your application.

Summary

  • Step 1: Define your edit form with CreateEditForm<Model, Entity>()
  • Step 2: Display the form inside a page using DisplayComponent
  • Step 3: Pass the ItemKey parameter to decide between "edit" or "create" mode
  • Tip: Use ParseOrEmpty to safely convert query parameters into valid key types

This setup makes it incredibly fast and consistent to manage entity forms across your application. Whether you're creating a new employee or editing an existing one, the framework handles data loading, model binding, validation, and saving — all based on your entity model.

Up next, we’ll explore how to customize the behavior, layout, and security of the EditForm with additional configuration options.

Configuring the EditForm Component

After you've created a basic EditForm using CreateEditForm<TModel, TKey>, you can fully customize its behavior, appearance, and security using the optional configuration callback. These options allow you to define how the form looks, who can edit what, and how it behaves after saving.

publicclassProgram

{

    publicstaticvoidMain(string[]args)

    {

        builder.CreateEditForm<EmployeeModel,Employee>("EmployeeEditForm",editForm=>

        {

// Control who can edit this form (e.g., only the employee with the same email)            editForm.CanEdit(a=>a.==CurrentUser.);

// Set a custom caption/title for the top of the form            editForm.Caption("This is my nice title for the edit form");

// Automatically navigate back (e.g., to the previous page) when save is successful            editForm.OnSuccessNavigateBack();

// Configure a specific property (in this case, Email)            editForm.PropertyOptions(a=>a.,options=>

            {

// Change the display label for the field                options.Label("Your Email");

// Add a helpful tooltip for the input                options.Tooltip("Please use the company email");

// Apply a custom CSS class to the input for styling                options.CssClass("company-email");

// Make the input read-only (shown, but not editable)                options.IsReadOnly();

// Completely hide the input field from the form                options.HideEditor();

// Use a custom Blazor component for this editor instead of the default input                options.EditorTemplate<CustomEditComponent>();

// Set a default value if the field is empty during creation                options.UseDefaultValue("your.name@company.com");

// Limit who is allowed to edit this field (by role)                options.AllowChangesToRoles("Admin","Manager");

            });

        });

    }

}

Breakdown of Configuration Options

Option Description When to Use
CanEdit(...) Sets a condition to control whether the form can be edited. Restrict edits to the entity owner or based on user permissions.
Caption(...) Sets a custom title at the top of the edit form. Personalize the form title based on the context or entity type.
OnSuccessNavigateBack() Navigates the user back after a successful save. Use in workflows where the user should return after editing.
PropertyOptions(...) Configures individual form fields with custom logic. Adjust labels, visibility, defaults, editors, and access control.

PropertyOptions Configuration

Each property inside your edit model can be configured individually using the PropertyOptions method. The available options include:

  • Label() – Sets a custom display label for the field
  • Tooltip() – Adds a hover tooltip with extra information
  • CssClass() – Adds a CSS class for styling the input
  • IsReadOnly() – Makes the field visible but not editable
  • HideEditor() – Hides the field completely from the form
  • EditorTemplate<TComponent>() – Replaces the default editor with a custom component
  • UseDefaultValue() – Provides a default value when creating a new entity
  • AllowChangesToRoles(...) – Restricts editing to specific roles

Why Use These Options?

These configuration tools give you full control over the user experience:

  • Show or hide fields depending on the scenario
  • Lock down fields that only admins can change
  • Use more advanced editors where needed
  • Provide default values to streamline data entry

With very little code, you can create forms that are not only functional but also smart, secure, and visually consistent across your application.

In the next section, we’ll explore how to design custom editor templates and how to split large edit forms into logical groups using form layouts.

Creating and Using Custom Editors in EditForm

In BlazorForKids, form inputs are automatically generated based on your entity model. However, there are cases where the default input controls are not enough — for example, when you want to replace a numeric input with a slider, or show a date picker with a custom layout.

To support this, BlazorForKids lets you replace the default editor for any property by providing a custom editor component. These custom editors can enhance the user experience and make your forms more interactive and visually consistent.

How to Build a Custom Editor

To create a reusable editor component, inherit from the base class BkEditorTemplate<TValue>. This base class already integrates with the Blazor form system by extending InputBase<TValue>, and it gives you access to all the settings and metadata you need to build a complete input control.

Example: Custom Range Slider (RangeBox)
// sample of a custom range slider editor

@typeparam TValue
@inherits BkEditorTemplate<TValue>

<div class="bk-field-box">
<label>@Settings.Label: </label>

@if (AdditionalAttributes is not null)
{
<div class ="bk-range">
<div class ="bk-range-min">
<span>@AdditionalAttributes["min"]</span>
</div>
<div class ="bk-range-editor" >
<span class ="bk-range-value" style = "--range-value:@Value">
@Value
</span >
<input type = "range" value = "@Value" @onchange = "OnValueChanged" step = "1" @attributes = "AdditionalAttributes"/>
</div>
<div class ="bk-range-max">
<span>@AdditionalAttributes["max"]</span>
</div>
</div>
}

<ValidationMessage For="ValueExpression" />
</div>

@code {

private async Task OnValueChanged(ChangeEventArgs arg)
{
if (arg.Value is not string stringValue) return;

if (TryParseValueFromString(stringValue, out var parsedValue, out var error) == false)
return;

Value = parsedValue;
await ValueChanged.InvokeAsync(Value);
}

}

This component visually replaces the standard number input with a range slider. It inherits from BkEditorTemplate<TValue>, so it's fully compatible with the framework's edit form pipeline.

Integration with the EditForm

To use your custom editor inside an EditForm, you can configure the target property using PropertyOptions(...) and set the editor via EditorTemplate<TCustomComponent>():

publicclassProgram

{

    publicstaticvoidMain(string[]args)

    {

        editForm.PropertyOptions(a=>a.YearsOfExperience,options=>

        {

            options.Label("Experience");

            options.EditorTemplate<BkRangeBox<int>>();

            options.UseDefaultValue(5);

            options.CssClass("experience-slider");

        });

    }

}

This will replace the input for YearsOfExperience with your custom BkRangeBox component, allowing users to adjust values using a slider instead of typing numbers.

What the Framework Provides

When inheriting from BkEditorTemplate<TValue>, the framework supplies everything you need:

  • Value – the current value of the field
  • ValueChanged – event to trigger when value changes
  • ValueExpression – used for validation
  • AdditionalAttributes – additional HTML attributes like min, max, or placeholder
  • Settings – includes metadata like Label and PropertyName

You can also override TryParseValueFromString() to customize how string input is parsed into your desired value type, enabling you to work with advanced types like decimals, enums, or custom structs.

Requirements for Custom Editors

To be compatible with the EditorTemplate<T> method in the form configuration, your component must:

  • Inherit from BkEditorTemplate<TValue>
  • Support two-way binding using the InputBase<T> base functionality
  • Render the necessary input elements and validation messages

Conclusion

With custom editor components, you can completely control how users interact with each field in your form. This opens the door to beautiful and intuitive form designs — sliders, tag selectors, inline dropdowns, switches, color pickers, and more — while keeping full compatibility with validation, permissions, and framework features.

Final Thoughts on EditForm

The EditForm component in BlazorForKids is designed to help you focus on what matters most — capturing and updating user data — without getting overwhelmed by form logic, validation, or UI consistency. Whether you're building a simple input form or a complex, role-based editor, the framework gives you the tools to make it fast, reliable, and visually consistent.

If you're just getting started, don't worry about mastering every feature at once. Begin with the basics: define your model, add the form to a page, and let the framework do the rest. As your app grows, you can explore advanced features like custom editors, conditional fields, access control, and layout customization.

Remember: you don’t need to build everything by hand. BlazorForKids is here to help you move faster and build smarter. And with just a few lines of configuration, you can create clean, powerful, and user-friendly forms that your users will love.

🧩 Start simple, grow with confidence — your forms are in good hands.

An unhandled error has occurred. Reload 🗙