Skip to content

Persisting Settings

Serenity 2.1.5 introduced ability to persist grid settings including these details:

  • Visible Columns and Display Order
  • Column Widths
  • Sorted Columns
  • Advanced Filters (ones created with Edit Filter link on bottom right)
  • Quick Filters (as of writing, not yet available)
  • State of Include Deleted Toggle

By default, grids don't automatically persist anything.

Thus, if you hide some columns and navigate away from Orders page, when you come back, you'll see that those hidden columns became visible again.

You need to turn on persistance for all grids, or for individual ones that you want them to remember their settings.

Turning On Persistance by Default

DataGrid has a static configuration parameter with name DefaultPersistanceStorage. This parameter controls where grids save their settings automatically by default. It is initially null.

In ScriptInit.ts, you might turn on persistance for all grids by default like below:

DataGrid.defaultPersistanceStorage = window.sessionStorage;

This saves settings to browser session storage, which is a key/value dictionary that preserves data while any browser window stays open. When user closes all browser windows, all settings will be lost.

Another option is to use browser local storage. Which preserves settings between browser restarts.

DataGrid.defaultPersistanceStorage = window.localStorage;

Using any of the two options, grids will start to remember their settings, between page reloads.

Handling a Browser that is Shared by Multiple Users

Both sessionStorage and localStorage is browser scoped, so if a browser is shared by multiple users, they'll have same set of settings.

If one user changes some settings, and logs out, and other one logs in, second user will start with settings of the first user (unless you clear localStorage on signout)

If this is a problem for your application, you may try writing a custom provider:

import { Authorization, SettingStorage } from '@serenity-is/corelib';

// ...

export class UserLocalStorage implements SettingStorage {
    getItem(key: string): string {
        return window.localStorage.getItem(Authorization.userDefinition.Username + ":" + key);
    }

    setItem(key: string, value: string): void {
        window.localStorage.setItem(Authorization.userDefinition.Username + ":" + key, value);
    }
}

// ...

DataGrid.defaultPersistanceStorage = new UserLocalStorage();

Please note that this doesn't provide any security. It just lets users have separate settings.

Setting Persistance Storage Per Grid Type

To turn on persistance, or change target storage for a particular grid, override getPersistanceStorage method:

import { SettingStorage } from '@serenity-is/corelib';

export class OrderGrid<P={}> extends EntityGrid<OrderRow, P> {
    // ...
        
    protected getPersistanceStorage(): SettingStorage {
        return window.localStorage;
    }
}

You may also turn off persistance for a grid class by returning null from this method.

Determining Which Setting Types Are Saved

By default, all settings noted at start are saved, like visible columns, widths, filters etc. You may choose to not persist / restore specific settings. This is controlled by gridPersistanceFlags method:

import { GridPersistenceFlags } from '@serenity-is/corelib';

export class OrderGrid<P={}> extends EntityGrid<OrderRow, P> {
    // ...
        
    protected gridPersistanceFlags(): GridPersistenceFlags {
        return {
            columnWidths: false // We don't want to save column widths
        };
    }
}

Here is the set of complete flags: GridPersistenceFlags

interface GridPersistenceFlags {
    columnPinning?: boolean;
    columnWidths?: boolean;
    columnVisibility?: boolean;
    sortColumns?: boolean;
    filterItems?: boolean;
    quickFilters?: boolean;
    quickFilterText?: boolean;
    quickSearch?: boolean;
    includeDeleted?: boolean;
    restoreOptions?: {
        newVisibleColumns?: boolean | null;
        onRevisionMismatch?: "reset" | "merge" | null;
    } | null;
}

restoreOptions is restore-only (it is not stored in the snapshot) and contains:

  • newVisibleColumns — whether newly added default-visible columns are shown, relative to their default neighbors, when a complete snapshot does not mention them. The default is true for the personal settings restored from storage, and false for the direct restores (e.g. saved views), which stay exact snapshots.
  • onRevisionMismatch — "reset" or "merge": what to do with the saved column layout when the columns revision differs from the saved one, see Columns Revision. The default is "reset" for the automatic restore and "merge" for a direct one.

Columns Revision

A columns script can have a Revision ([ColumnsScript(Revision = 2)]), which the client receives with the columns. When the current revision is positive and differs from the one saved with the user's settings (including an absent revision), a personal restore resets the saved column order, visibility, widths and pinning to their initial values, while keeping the saved sorting and filters. 0 disables the check. The "reset" default is what you want after a change that makes the old layout meaningless (e.g. columns moved to another type); "merge" keeps the saved layout and only adds the new columns.

[ColumnsScript(Revision = 2)]
public class OrderColumns { /* ... */ }

The revision is sent in the normal and the compact property item scripts and recorded with the persisted columns, so a deployment that bumps it resets the layouts of the users once.

Persistence Events

DataGrid.onPersistence runs before and after the settings are captured as well as restored, so a handler can adjust flagsToUse before the capture. Its arguments (DataGridPersistenceEvent) tell whether it is the after phase (after), whether the grid is restoring or persisting, whether it is an automaticRestore, and whether a columnResized triggered the save. A restore reports columnLayoutReset and columnWidthsRestored afterwards, so a handler can tell what the restore actually did.

When Settings Are Saved / Restored

Settings are automatically saved when you change something with a grid like:

  • Choosing visible columns with Column Picker dialog
  • Resizing a column manually
  • Editing advanced filter
  • Dragging a column, changing position
  • Changing sorted columns

Settings are restored on first page load, just after grid creation.

Persisting Settings to Database (User Preferences Table)

Serene comes with a UserPreferences table that you may use as a persistance storage. To use this storage, you just need to set it as storage similar to other storage types.

The server side UserPreferenceRepository converts the identifier of the current user to the type of the user ID field, so the preferences work when the user id is a Guid, a 64-bit integer or a string. An update without a user identifier (e.g. on an anonymous request) throws a NotLoggedIn validation error, and a retrieve returns an empty response, instead of saving or querying a preference that no user owns. A subclass can resolve the id in another way by overriding GetUserId().

In ScriptInit.ts

import { UserPreferenceStorage } from '@serenity-is/extensions';

DataGrid.defaultPersistanceStorage = new UserPreferenceStorage();

OR

import { SettingStorage } from '@serenity-is/corelib';
import { UserPreferenceStorage } from '@serenity-is/extensions';


export class OrderGrid<P={}> extends EntityGrid<OrderRow, P> {
    // ...
        
    protected getPersistanceStorage(): SettingStorage {
        return new UserPreferenceStorage();
    }
}

Manually Saving / Restoring Settings

If you need to save / restore settings manually, you may use methods below:

protected getCurrentSettings(flags?: GridPersistenceFlags): PersistedGridSettings;
protected restoreSettings(settings?: PersistedGridSettings, flags?: GridPersistenceFlags): void;
protected getColumnsRevision(): number;

These are protected methods of DataGrid, so can only be called from subclasses. Pass restoreOptions in the flags of restoreSettings to restore a snapshot exactly (as saved views do) or to reset it on a revision mismatch.

The old misspelled type name GridPersistanceFlags (and the gridPersistanceFlags method that it types) is kept as a deprecated alias for backwards compatibility; new code should use GridPersistenceFlags.