MSBA-271 · Lesson 2 of 12 · 20 min
Form events and the client API
▶ Video coming soon A video version of this lesson is on the way.
The second session started with a complaint from Bronwyn, one of the two Lakeshore dispatchers. When she opened a work order from the dispatch board, the Contractor section sometimes appeared for a split second and then vanished, and twice she had typed into a field that was then cleared by a script. Signe used it as the lesson. "Everything a form script does happens inside an event," she said. "If you do not know which event you are in, and what has and has not happened yet, the form will surprise people."
The events a form raises
A model-driven form raises events at predictable points: when it opens, when data arrives, when a column changes, when the user saves, and after the save. Some events can be registered in the form designer; others only from code. Knowing the difference matters because a handler registered in the designer is stored with the form, travels in the solution and runs every time, while a handler added from code exists only after the code that adds it has run.
| Event | Raised when | Register in the designer? | Add or remove from code |
|---|---|---|---|
| Form data OnLoad | Data for the row has been loaded, including after a save or refresh | No | formContext.data.addOnLoad |
| Form OnLoad | The form opens | Yes | formContext.ui.addOnLoad |
| Loaded | The form has finished loading its user interface | No | formContext.ui.addLoaded |
| Column OnChange | A column's value changes and the user leaves the field, or code calls fireOnChange | Yes | getAttribute(...).addOnChange |
| OnSave | A save is requested | Yes | formContext.data.entity.addOnSave |
| PostSave | The save has finished | No | formContext.data.entity.addOnPostSave |
| Lookup PreSearch | Just before a lookup shows its results | No | getControl(...).addPreSearch |
| Tab state change | A tab is expanded or collapsed | No | tab.addTabStateChange |
Bronwyn's flicker came from a handler that set section visibility only on OnChange of Category. On load the section showed with its default visibility, and the script corrected it only when someone touched Category, or when a later handler fired the change event. The fix was the pattern in lesson 1: run the same function once in OnLoad and again in OnChange, so the form starts in the right state. The cleared field was a different mistake. A second library, written for an earlier pilot, set Priority to a default every time the form loaded, even for existing rows. Signe showed Wiremu how to check the form type first.
function onLoad(executionContext) {
var formContext = executionContext.getFormContext();
var formType = formContext.ui.getFormType(); // 1 = create, 2 = update
if (formType === 1) {
var priority = formContext.getAttribute("lcc_priority");
if (priority && priority.getValue() === null) {
priority.setValue(100000001); // example value for Normal
}
}
}Registering handlers well
In the form designer, a handler names the library, the function and the event. Two options matter. Pass execution context as first parameter should almost always be selected, because without it the function has no reliable way to reach the form. And parameters can pass fixed values, such as a section name, so that one function can serve several handlers. A form can have up to 50 handlers for one event. They run in the order shown in the form properties, so a handler that depends on another must come after it.
Handlers can share information through the execution context. setSharedVariable and getSharedVariable store and read values that later handlers for the same event can see, which avoids global variables. getDepth tells a handler where it sits in a chain of events, which helps when one handler sets a value that fires another OnChange.
Registering handlers from code, with addOnChange and similar methods, suits handlers that depend on conditions, such as attaching a change handler only for some form types, and events the designer does not offer, such as PreSearch. The cost is that code-registered handlers are invisible in the designer. Lumenvale's convention was to register from the designer wherever possible and to list any code-registered handlers in a comment at the top of the library.
One trap catches nearly every newcomer: setValue does not fire OnChange. If a script sets Category and other logic depends on Category's change event, the script must call fireOnChange on the attribute afterwards. Equally, a handler that responds to OnChange by setting the same column can loop if it calls fireOnChange carelessly. getDepth and a simple "already handled" check stop that.
OnSave and canceling a save
OnSave handlers run when a save is requested, whether by the Save command, by autosave or by script. The handler receives an execution context whose getEventArgs() returns save event arguments. preventDefault() on those arguments cancels the save; getSaveMode() tells the handler why the save happened, so a handler can, for example, allow autosave but check more carefully when the user chooses Save and Close.
function onSave(executionContext) {
var formContext = executionContext.getFormContext();
var args = executionContext.getEventArgs();
var status = formContext.getAttribute("lcc_status").getValue();
var photos = formContext.getAttribute("lcc_photocount").getValue() || 0;
if (status === 100000004 && photos === 0) { // example value for Closed
args.preventDefault();
formContext.ui.setFormNotification(
"Add at least one photo before closing a safety job.",
"ERROR", "lcc_photo_required");
} else {
formContext.ui.clearFormNotification("lcc_photo_required");
}
}The check above duplicates the BlockSafetyCloseWithoutPhoto plug-in designed in MSBA-270, on purpose. The plug-in is the rule; the script is a courtesy that catches the problem before the round trip and puts a clear message where the dispatcher is looking. If the script and the plug-in ever disagree, the plug-in wins, and Signe asked that both be changed together in the same pull request.
Forms also support asynchronous OnLoad and OnSave handlers: a handler can return a promise and the platform waits for it, up to a time limit, before continuing. This is the supported way to check something on the server before allowing a save, for example asking a custom API whether a room is closed for maintenance. Asynchronous handlers must be turned on in the app's settings, and they should be quick, because the user is waiting.
Navigation, dialogs and notifications
Scripts often need to take the user somewhere or tell them something. Xrm.Navigation opens forms, lists, web resources, custom pages and dialogs; notifications put messages on fields, forms or the whole app. Choosing the right one is a usability decision as much as a technical one.
| Method | What it does |
|---|---|
| Xrm.Navigation.openForm | Opens a table form for a new or existing row, optionally with default values |
| Xrm.Navigation.navigateTo | Opens a page: a table list, a form, an HTML web resource or a custom page, inline or as a dialog |
| Xrm.Navigation.openAlertDialog | Shows a message with one button |
| Xrm.Navigation.openConfirmDialog | Asks the user to confirm or cancel |
| Xrm.Navigation.openErrorDialog | Shows an error with details the user can copy |
| Xrm.Navigation.openUrl | Opens an address in a new window |
| Xrm.Navigation.openFile | Opens or saves a file returned by code |
Custom pages are worth a short explanation here, because navigateTo is how scripts reach them. A custom page is a canvas page designed in the canvas designer but stored and run as part of a model-driven app. It can show data from many tables and connectors in a free layout, which a form cannot. Scripts and commands open custom pages with navigateTo, passing the page name and, often, a row ID as a parameter; the page reads it with the Param function. At Lumenvale, the dispatch board was a generative page, but the room booking dialog that Maribeth wanted for the registrar was planned as a small custom page opened from a command, as a dialog sized to the content.
function openRoomBooking(primaryControl) {
var id = primaryControl.data.entity.getId().replace(/[{}]/g, "");
var pageInput = {
pageType: "custom",
name: "lcc_roombooking_8a1f2", // example logical name of the custom page
entityName: "lcc_room",
recordId: id
};
var options = { target: 2, position: 1, width: { value: 50, unit: "%" }, title: "Book this room" };
return Xrm.Navigation.navigateTo(pageInput, options);
}The difference between field and form notifications is a favorite exam point. A control notification, set with setNotification on a control, shows a message next to the field and stops the form from saving until it is cleared with clearNotification. A form notification, set with formContext.ui.setFormNotification, shows a banner at the top of the form with a level of ERROR, WARNING or INFO, and does not block saving on its own. A global notification, added with Xrm.App.addGlobalNotification, appears across the app and can include an action button. Each notification has a unique ID so that the same code can clear it later; forgetting to clear is how forms end up with stale warnings.
Dialogs are the strongest tool and should be used least. An alert or confirm dialog stops the user until they respond, which is right before an irreversible action and wrong for anything routine. Bronwyn had complained about a confirm dialog that appeared every time she changed Priority. Wiremu replaced it with a form notification that appeared only for Urgent, and the complaint stopped.
Grids and lookups
Form scripts can work with subgrids through the grid context. A subgrid control gives access to its rows, a refresh method and an OnLoad event that fires when the grid loads or refreshes. Editable grids add their own events for row selection and cell changes. Lookups have the PreSearch event, which lets a script add a filter just before results appear. At Lumenvale the Room lookup on the work order was filtered to the building chosen in the Building column, which a related-records filter could do on its own; but the Asset lookup also had to exclude assets with a status of Retired, and that extra condition needed addCustomFilter in a PreSearch handler.
function onLoadAddAssetFilter(executionContext) {
var formContext = executionContext.getFormContext();
var assetControl = formContext.getControl("lcc_asset");
if (!assetControl) { return; }
assetControl.addPreSearch(function () {
var fetch = "<filter type='and'>" +
"<condition attribute='lcc_status' operator='ne' value='100000002' />" + // example value for Retired
"</filter>";
assetControl.addCustomFilter(fetch, "lcc_asset");
});
}Worked problem
Picking the right event
Maribeth wants three behaviors on the transcript request form: when Delivery Method changes to Electronic, clear the mailing address and hide its section; before saving a request marked Urgent, ask the officer to confirm the fee; and after saving, refresh the Deliveries subgrid. Which event and which Client API features does each need?
Show solution
- Clearing and hiding on a change belongs in the OnChange handler of Delivery Method, plus OnLoad so the form opens correctly. It uses setValue(null) on the address attributes and setVisible on the section.
- Confirming before a save belongs in OnSave. Because it waits for the user, the handler must cancel the save with preventDefault, show openConfirmDialog, and save again from the dialog's promise if the officer confirms, or use an asynchronous save handler if the app has them enabled.
- Refreshing a subgrid after the save belongs in PostSave, which runs once the server has finished, using the grid control's refresh method.
Answer: OnChange and OnLoad for the delivery method; OnSave with a confirm dialog for the fee; PostSave with a subgrid refresh. Each behavior sits in the event that matches when it must happen.
Keeping form scripts maintainable
Form scripts outlive the people who write them, so Signe asked Wiremu to treat every handler as code someone else would maintain. Her checklist was short. Keep each handler small and named for what it does, such as onRoomChange, inside the Lumenvale namespace. Read the form context from the execution context, never from a global. Never reach into the page's HTML to find or change elements, because the page structure is not supported and changes without notice; use the Client API instead. And before writing a script at all, check whether a business rule or a column setting can do the job, because those survive upgrades with no maintenance.
| Need | Best tool | Why |
|---|---|---|
| Make a column required when another has a value | Business rule | No code, runs on the form and can run on the server |
| Show or hide a section by status | Business rule, or a script if the logic is complex | Simple conditions need no code |
| Set a value retrieved from a related row | Script with Xrm.WebApi | Business rules cannot read related rows |
| Filter a lookup by another column | Script with addPreSearch and addCustomFilter | Lookup filtering by script is the supported route |
| Enforce a rule for every way data arrives | Server-side logic, not a form script | Form scripts run only on the form |
Testing a form script means more than opening the form once. Wiremu tested each change with the Facilities Dispatcher, Facilities Technician and Facilities Manager roles, because a script that sets a column the user cannot edit fails differently from one that works for an administrator. He also opened the form on a phone, where some tabs are collapsed and the form factor differs; the client's getFormFactor method lets a script adjust when it must, though most scripts should behave the same everywhere.
Common mistakes
MistakeSetting form state only in OnChange.
InsteadCall the same function from OnLoad so the form opens in the right state.
MistakeExpecting setValue to fire OnChange.
InsteadCall fireOnChange on the attribute when dependent logic must run.
MistakeUsing a dialog for routine messages.
InsteadUse form or control notifications; keep dialogs for decisions that need an answer.
MistakeForgetting to clear notifications.
InsteadGive each a unique ID and clear it when the condition no longer applies.
MistakeNot selecting the option to pass the execution context.
InsteadSelect it for every handler, so the function can reach the form reliably.
Before the session ended, Bronwyn opened the updated form in Facilities Dev. The Contractor section stayed hidden, her priority stayed as she had set it, and the urgent-job warning appeared once, as a banner. She asked whether she could have the same behavior on the dispatch board. Signe wrote that down for the session on commands.
Summary and key terms
- Forms raise events in order: data OnLoad, form OnLoad, Loaded, column OnChange, OnSave and PostSave, plus control events such as PreSearch.
- Only OnLoad, OnSave and column OnChange can be registered in the designer; others are added from code. Up to 50 handlers can run per event, in the listed order.
- Pass the execution context to every handler; use shared variables and getDepth rather than globals.
- OnSave handlers can cancel a save with preventDefault and check the save mode; asynchronous handlers are supported when enabled.
- Xrm.Navigation opens forms, lists, custom pages and dialogs; navigateTo is how scripts and commands open custom pages.
- Control notifications block saving until cleared; form and global notifications do not.
- Event handler
- A registration that tells the form which function to call when an event occurs.
- Save event arguments
- The object from getEventArgs in an OnSave handler, used to cancel a save or read the save mode.
- Control notification
- A message shown next to a field that blocks saving until it is cleared.
- Form notification
- A banner at the top of a form with an error, warning or information level.
- Custom page
- A canvas page stored and run inside a model-driven app, opened through navigation or commands.
- PreSearch
- A lookup control event raised just before results are shown, used to add filters.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why did the Contractor section flicker on Bronwyn's form, and what fixed it?
Show answer
Visibility was set only in OnChange, so the form opened in its default state; calling the same function from OnLoad set the right state from the start.
Which kind of notification stops the form from saving?
Show answer
A control notification set with setNotification, until it is cleared.
How can a script add a filter that a related-records filter cannot express?
Show answer
Add a PreSearch handler to the lookup control and call addCustomFilter with a FetchXML filter.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.