Form models

Forms with fields your entity doesn't have

Introduction

By default, the create and edit pages bind their fields to the resource's entity. When a form needs fields the entity doesn't have, such as a password confirmation or a reason for a change, you can give the page its own form model.

On an EF Core resource, the form model wraps the entity, and StellarAdmin still loads and saves the entity for you. On any resource, you can instead write a handler that saves the form model yourself.

Wrapping the entity in a form model

Sometimes you may want to capture additional fields that are not on the resource model. For example, let's say your edit pages contains a field where the user must enter the reason for changing the resource. In situations like this, you can wrap the resource model inside a form model.

In the example below, we created a form model for trips that holds the Trip resource, and an additional property named Reason to capture the reason the user changed the trip.

public class EditTripForm
{
    public Trip Trip { get; set; } = null!;

    [Required, StringLength(500)]
    [Display(Name = "Reason for the change")]
    public string Reason { get; set; } = "";
}

To use the form model, call AllowEdit() with the form model as the type argument, and a lambda that specifies the property that holds the resource. If you use form events, the form model is passed to the event, rather that the resource/entity.

The example below adds the reason to an audit entry in OnUpdating:

admin.AddEfCoreResource<Trip>(resource =>
{
    resource.AllowEdit<EditTripForm>(form => form.Trip, edit =>
    {
        edit.Fields(fields =>
        {
            fields.Add(form => form.Trip.Title);
            fields.Add(form => form.Trip.BasePrice);
            fields.Add(form => form.Trip.DestinationId);
            fields.Add(form => form.Trip.Tags);
            fields.Add(form => form.Reason);
        });
        edit.Events(events =>
            events.OnUpdating = (context, cancellationToken) =>
            {
                context.Db.Add(new TripChange
                {
                    TripId = context.Entity.Id,
                    Reason = context.Model.Reason,
                    ChangedAt = DateTimeOffset.UtcNow,
                });

                return Task.CompletedTask;
            }
        );
    });
});

When using a form model with AllowCreate(), be sure to initialize the resource property on the form model.

public class CreateTripForm
{
    public Trip Trip { get; set; } = new();

    [Required, StringLength(500)]
    [Display(Name = "Reason for the addition")]
    public string Reason { get; set; } = "";
}

Saving a form model with a handler

A handler allows you to write completely custom code to create or save a resource.

The example below adds a create page that gives a new guide a sign-in. Call AllowCreate() with the form model and the handler as type arguments:

admin.AddEfCoreResource<Guide>(resource =>
{
    resource.AllowCreate<NewGuideForm, NewGuideHandler>(create => create.Fields(fields =>
    {
        fields.Add(form => form.FirstName);
        fields.Add(form => form.LastName);
        fields.Add(form => form.Email);
        fields.Add(form => form.Password);
        fields.Add(form => form.ConfirmPassword);
    }));
});

The form model has a property for each field, with the attributes that validate it:

public class NewGuideForm
{
    [Required, Display(Name = "First name")]
    public string FirstName { get; set; } = "";

    [Required, Display(Name = "Last name")]
    public string LastName { get; set; } = "";

    [Required, EmailAddress]
    public string Email { get; set; } = "";

    [Required, DataType(DataType.Password)]
    public string Password { get; set; } = "";

    [Compare(nameof(Password)), DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    public string ConfirmPassword { get; set; } = "";
}

When someone saves the form, StellarAdmin calls the handler's CreateAsync() method with the form model. The example below saves the guide and sets the password:

using StellarAdmin.Resources;

public class NewGuideHandler(ApplicationDbContext db, GuideAccounts accounts)
    : IResourceCreateHandler<NewGuideForm>
{
    public async Task<ResourceOperationResult> CreateAsync(
        NewGuideForm form, CancellationToken cancellationToken)
    {
        var guide = new Guide { FirstName = form.FirstName, LastName = form.LastName, Email = form.Email };
        db.Guides.Add(guide);
        await db.SaveChangesAsync(cancellationToken);
        await accounts.SetPasswordAsync(guide, form.Password, cancellationToken);

        // The key lets a lookup that opened the create page select the new guide
        return ResourceOperationResult.Success(guide.Id.ToString());
    }
}

StellarAdmin registers the handler as a scoped service, unless you've registered it already, so the handler can take any service in its constructor. To reject the form, return validation errors the same way a data source does.

Available handlers

Each page that can use a form model has its own handler interface. Pass the handler as the second type argument of the page's method:

PageMethodHandler interfaceHandler methods
CreateAllowCreate<TModel, THandler>()IResourceCreateHandler<TModel>CreateAsync() saves the new record and returns its key.
EditAllowEdit<TModel, THandler>()IResourceEditHandler<TModel>FindAsync() loads the form model for a record, and UpdateAsync() saves it.
ViewAllowView<TModel, THandler>()IResourceViewHandler<TModel>FindAsync() loads the model the view page displays.

Handlers do not require custom models. You can use the resource model itself, for example AllowCreate<Booking, BookingHandler>() with a BookingHandler that implements IResourceCreateHandler<Booking>.

On this page