Form events
Run your own code when an EF Core create or edit form loads or saves a record
Introduction
When using EF Core resources, StellarAdmin exposes a number of events that allow you to perform additional work such as writing an audit entry. To add events, call Events() in the callback of AllowCreate() or AllowEdit(), and set the delegate of each event you need.
The example below sets the creation time of a new booking before it's saved:
resource.AllowCreate(create =>
{
create.Fields(fields =>
{
fields.Add(booking => booking.TravellerId);
fields.Add(booking => booking.DepartureId);
});
create.Events(events =>
events.OnCreating = (context, cancellationToken) =>
{
context.Entity.CreatedAt = DateTimeOffset.UtcNow;
return Task.CompletedTask;
}
);
});StellarAdmin supports the following events:
| Event | Form | Runs |
|---|---|---|
OnInitialized | Create | Before a create form is displayed. |
OnCreating | Create | Before a new record is saved. |
OnCreated | Create | After a new record is saved. |
OnLoaded | Edit | After the edit form loads the record. |
OnUpdating | Edit | Before the changes to a record are saved. |
OnUpdated | Edit | After the changes to a record are saved. |
Each event receives a context with the following properties:
| Property | Contains |
|---|---|
Db | The DbContext that loads and saves the record. |
Entity | The entity the form creates or edits. |
Entry | The entity's change tracking entry, whose original values are the stored ones when the form edits a record. Only in OnCreating and OnUpdating. |
Model | The model the form binds to. It's the same object as Entity, unless the form uses its own form model. |
Services | The request's services. |
Rejecting a save
To stop a record from being saved, call Fail() in OnCreating or OnUpdating. StellarAdmin displays the form again with the values that were entered and the error, and rolls back the transaction. The Fail() method has the following overloads:
| Overload | Displays the error |
|---|---|
Fail(message) | Above the form. |
Fail(field, message) | Under the field that field selects, such as trip => trip.BasePrice. |
We suggest you always use normal validation when possible, but there are scenarios where simple validation rules won't suffice. Suppose you want to ensure a price does not drop by more that half when updating. For a rule like this, you need the previous value.
Since you have access to EF Core's entity tracking entry in the OnUpdating event via the Entry property of the context, you can easily compare the current and previous values, which allows you to implement such a rule.
edit.Events(events =>
events.OnUpdating = (context, cancellationToken) =>
{
var original = context.Entry.Property(trip => trip.BasePrice).OriginalValue;
if (context.Entity.BasePrice < original / 2)
{
context.Fail(trip => trip.BasePrice, "The price can't drop by more than half in one change.");
}
return Task.CompletedTask;
}
);Handling saving of records
Sometime records must be saved through a service and not via the DbContext. A prime example of this is when you want to manage users with StellarAdmin. ASP.NET Core Identity allows you to read and query users via the DbContext, but users must be saved using UserManager, which hashes the password and normalizes the email address.
create.Events(events =>
events.OnCreating = async (context, cancellationToken) =>
{
var users = context.Services.GetRequiredService<UserManager<ApplicationUser>>();
context.Entity.UserName = context.Entity.Email;
var result = await users.CreateAsync(context.Entity, context.Model.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
context.Fail(error.Description);
}
return;
}
context.Handled();
}
);Call the Handled() method on the context to indicate to StellarAdmin that you saved the record and it should not attempt to save the record itself. Call Fail() when an error occurs. StellarAdmin will display the error message to the user and roll back the transaction.
The example above also uses a custom model to handle password confirmation during creation. You can read more in the form models documentation.
Running code after a record is saved
OnCreated and OnUpdated run after the transaction is committed. Use them for work that must only happen once the record is saved, such as sending an email. The example below sends a confirmation for a new booking:
create.Events(events =>
events.OnCreated = async (context, cancellationToken) =>
{
var email = context.Services.GetRequiredService<IBookingEmails>();
await email.SendConfirmationAsync(context.Entity, cancellationToken);
}
);The record is already saved, so these events can't reject the save.
Using an events class
When the events need services, place them in a class. The class must inherit from EfCoreCreateEvents<TEntity, TModel> or EfCoreEditEvents<TEntity, TModel>, and override the methods of the events it needs, such as CreatingAsync() or UpdatingAsync(). TModel is the entity type, unless the form uses its own form model.
The example below sets the user who created a booking:
using StellarAdmin.EntityFrameworkCore;
public class BookingEvents(IHttpContextAccessor http) : EfCoreCreateEvents<Booking, Booking>
{
public override Task CreatingAsync(
EfCoreSaveContext<Booking, Booking> context, CancellationToken cancellationToken)
{
context.Entity.CreatedBy = http.HttpContext!.User.Identity!.Name!;
return Task.CompletedTask;
}
}To use the class, call UseEvents() with the class as the type argument:
resource.AllowCreate(create =>
{
create.Fields(fields => fields.Add(booking => booking.DepartureId));
create.UseEvents<BookingEvents>();
});StellarAdmin registers the class as a scoped service, unless you've registered it already, so its constructor can take any service. An events class replaces any delegates set with Events().