Skip to content

EntityDialog and CRUD Workflows

EntityDialog is the base class for edit dialogs in Serenity. It hosts a PropertyGrid for editing an entity and provides the full CRUD workflow: loading (retrieve), saving (create/update), deleting, undeleting, and the toolbar buttons that drive these operations.

The Dialog Hierarchy

Class Purpose
BaseDialog Base dialog with modal/panel behavior, title, and buttons.
PropertyDialog A dialog that edits a single entity's properties with a property grid and OK/Cancel buttons.
EntityDialog The full CRUD dialog: property grid + save/delete/undelete + localization + toolbar buttons.

Creating an EntityDialog

A typical generated dialog extends EntityDialog and overrides a few methods:

export class LanguageDialog<P = {}> extends EntityDialog<LanguageRow, P> {
    static override[Symbol.typeInfo] = this.registerClass(nsAdministration);

    protected override getFormKey() { return LanguageForm.formKey; }
    protected override getRowDefinition() { return LanguageRow; }
    protected override getService() { return LanguageService.baseUrl; }
}
Method Purpose
getFormKey() The form script key (e.g. LanguageForm.formKey).
getRowDefinition() The row class (provides permissions, id property, etc.).
getService() The service base URL (e.g. LanguageService.baseUrl).

The Lifecycle

Initialization

An entity dialog supports deferred initialization (Attributes.deferInit("optional")), so it loads its form either in its constructor or in deferredInit(), e.g. asynchronously, once the constructors of its subclasses are done — see Deferred Initialization. Either way the steps are:

  1. getPropertyItemsData() loads the form's PropertyItem[], or getPropertyItemsDataAsync() when the dialog defers its initialization.
  2. propertyItemsReady() calls initPropertyGrid() and initLocalizer().
  3. afterInit() is called as a hook for subclasses.

init() returns at once, and initAsync() resolves once the form and the lookups of its editors are there. Anything that needs the form waits for the dialog itself, so opening a dialog doesn't change: load, loadById, loadByIdAndOpenDialog, loadEntityAndOpenDialog, loadNewAndOpenDialog and dialogOpen wait for it, and the callbacks of the load methods run after it, with the entity loaded. readOnly can be set before it, and is applied when the dialog loads an entity.

Loading an Entity

load(entityOrId, done, fail) loads an entity into the dialog:

  • If entityOrId is null, a new empty entity is loaded.
  • If it's a string/number, the dialog calls the retrieve service (.../Retrieve) via loadById().
  • If it's an object, it's loaded directly.
dialog.load(entityOrId, () => {
    dialog.dialogOpen(asPanel);
});

Once the record is in the form, the dialog raises onAfterLoadEntity, on the class (for every entity dialog) and on the instance, with the dialog as the argument:

EntityDialog.onAfterLoadEntity.subscribe(({ dialog }) => {
    // the record of any entity dialog is loaded
});

this.onAfterLoadEntity.subscribe(({ dialog }) => {
    // the record of this dialog is loaded, e.g. to load its related rows
});

entityType gives the entity type of the dialog, e.g. Northwind.Order, which is its class name without its root namespace and Dialog suffix unless the dialog overrides getEntityType(). BaseDialog.onAfterInit tells when a dialog is initialized, once for its whole life; see Dialog Addons for the features that subscribe to these events.

Saving

save(callback, initiator) validates the form, builds a SaveRequest, and calls the save service (.../Create or .../Update):

  1. validateBeforeSave() — validate the form (override to add custom validation).
  2. getSaveRequest() — builds the SaveRequest from the property grid values.
  3. saveHandler() — calls the service.
  4. onSaveSuccess() — handles the response (e.g. notifying the grid to refresh).

Deleting and Undeleting

  • doDelete(callback) — calls the delete service (.../Delete).
  • undelete(callback) — calls the undelete service (.../Undelete).

Both show a confirmation dialog first.

Toolbar Buttons

getToolbarButtons() builds the standard buttons:

Button Action
Save and Close Saves and closes the dialog.
Apply Changes Saves and reloads the entity (stays open).
Delete Deletes the entity (edit mode, not deleted).
Undelete Restores a deleted entity.
Edit Switches from view mode to edit mode.
Clone Creates a copy of the entity.
Localization Opens the localization dialog.

Each button's visibility and disabled state are controlled by the dialog's mode and permissions:

saveAndCloseToolButton({
    onClick: async () => {
        if (!(await this.commitEdits()))
            return;
        this.save(() => this.dialogClose("save-and-close"), "save-and-close")
    },
    visible: () => !this.isDeleted() && !this.isViewMode(),
    disabled: () => !this.hasSavePermission() || this.readOnly,
    ref: el => this.saveAndCloseButton = Fluent(el)
})

Permissions

The dialog checks permissions from the row definition:

Method Permission
hasSavePermission() Row's insertPermission/updatePermission.
hasDeletePermission() Row's deletePermission.
hasUndeletePermission() Row's undeletePermission.

The Undelete button checks hasUndeletePermission() — the row metadata's undeletePermission (from [UndeletePermission], falling back to the delete, modify, then read permission) — instead of the delete permission, so restoring a record can be authorized separately from deleting it.

Optimistic Concurrency

If the row definition has a concurrencyVersionProperty (emitted for rows implementing IConcurrencyVersionRow), the dialog copies the version value from the loaded entity into the save request, even though the read-only version field has no form field. This lets the server detect a record that was modified or deleted by someone else since it was loaded, and raise a ConcurrencyConflict validation error — see Optimistic Concurrency.

Modes

The dialog has several modes:

  • Edit mode — editing an existing entity.
  • Insert mode — creating a new entity.
  • View mode — read-only view (with an Edit button).
  • Deleted — the entity is soft-deleted (shows Undelete).

These are checked with isEditMode(), isViewMode(), isDeleted(), etc.

Dialog Size and Scrolling

The DialogOptions of a Bootstrap modal decide its size and how it scrolls (DialogOptions):

  • height — "auto" (the default, sizes the modal to its content), "md", "lg" or "full". A modal with a fixed height keeps its size and position while its content changes, and its body scrolls. "md" and "lg" take the new --s-modal-height-md (40rem) and --s-modal-height-lg (48rem) tokens, "full" the height of the viewport, and all of them are capped to it.
  • centered — true (the default) centers the modal. When false, it is placed at the --s-modal-top token (max(1.75rem, 8dvh)) instead of the top of the viewport, so it grows downwards instead of moving as its content grows, and with scrollable its body scrolls once it reaches the bottom of the viewport.
  • scrollable — adds the modal-dialog-scrollable class of Bootstrap (it used to add modal-scrollable, which does not exist), so the body of the dialog scrolls instead of the page.

The rules are in modal-layout.css of Serenity.Extensions, which the Serene and StartSharp bundles import.

On a narrow screen a dialog can open as a panel instead of a modal (openDialogsAsPanel), which takes the place of the page content. A panel is scrolled into view when it opens, and the scroll position of the page, saved before the content is hidden, is restored when it closes, so the user returns to the row that opened it.

See Also