Setting default values

Set the values a new record starts with

Introduction

StellarAdmin provides a number of ways to initialize values for a new instance of a resource model.

  • UseFactory() allows you to create a new instance and is useful for resources without a parameterless constructor and for setting simple defaults, such as a date or a status.
  • The OnInitialized form event is available for EF Core resources. It is passed an initialized instance before the form is displayed and is useful for generating default values that runs async code or require services from DI.
  • The OnCreating form event is available for EF Core resources. It runs when the user saves the form and is useful for generated values such as a booking reference.

The following table compares them:

UseFactory()OnInitializedOnCreating
Available onAll resourcesOnly EF Core resourcesOnly EF Core resources
Runs before the form is displayedYesYesNo
Runs when the record is savedYesNoYes
Can use services and async codeNoYesYes
Creates the modelYesNoNo

Setting simple defaults

As mentioned above, the UseFactory() method is useful for creating a new instance and setting simple default values. The example below starts a departure six weeks away, with a meeting time of 9:00 and a status of Scheduled:

resource.AllowCreate(create =>
{
    create.UseFactory(() => new Departure
    {
        StartDate = DateOnly.FromDateTime(DateTime.Today.AddDays(42)),
        MeetingTime = new TimeOnly(9, 0),
        Status = DepartureStatus.Scheduled,
    });
    create.Fields(fields =>
    {
        fields.Add(departure => departure.TripId);
        fields.Add(departure => departure.StartDate);
        fields.Add(departure => departure.MeetingTime);
    });
});

Setting default values that need services

If your initialization code needs to use service or run async code, you can use the OnInitialized form event, which is available on EF Core Resources.

The example below starts a new departure with a meeting point that is read from the database:

resource.AllowCreate(create =>
{
    create.Fields(fields =>
    {
        fields.Add(departure => departure.TripId);
        fields.Add(departure => departure.MeetingPoint);
    });
    create.Events(events =>
        events.OnInitialized = async (context, cancellationToken) =>
            context.Entity.MeetingPoint = await context.Db.Set<Setting>()
                .Select(setting => setting.DefaultMeetingPoint)
                .FirstAsync(cancellationToken)
    );
});

StellarAdmin runs OnInitialized wherever it displays a create form: on the create page, in a new inline row, in the create sheet of a lookup, and in the next form after saving and adding another, before it applies the values that are kept. It doesn't run when someone saves the form, so set values that must be set when the record is saved in OnCreating, as described below.

Setting values when the record is saved

For unique generated values that must be generated once, such as a booking reference, UseFactory() is not a good option since it runs twice - before the form is displayed and when the record is saved. For EF Core resources, a better option is to generate the value in the OnCreating form event, which runs once, before the record is saved:

resource.AllowCreate(create =>
{
    create.UseFactory(() => new Booking { Reference = "", Status = BookingStatus.Pending });
    create.Fields(fields =>
    {
        fields.Add(booking => booking.TravellerId);
        fields.Add(booking => booking.DepartureId);
    });
    create.Events(events =>
        events.OnCreating = (context, cancellationToken) =>
        {
            context.Entity.Reference = $"VT-{Random.Shared.Next(0, 1_000_000):D6}";

            return Task.CompletedTask;
        }
    );
});

Setting values with a custom data source

The OnInitialized and OnCreating form events are only available on EF Core resources. With a custom data source, set defaults with UseFactory(), and set values when the record is saved in the data source's CreateAsync() method, or in a create handler.

On this page