MSBA-271 · Lesson 1 of 12 · 22 min

Client scripting with JavaScript

▶ Video coming soon A video version of this lesson is on the way.

In the second half of the fall term, Signe Tavernier-Mbeki turned her developer design reviews into a hands-on series for Wiremu Quaresma. The design reviews had settled where each piece of logic should live. This series was about the part of the work Wiremu had been waiting for: code that changes what people see and do in Lumenvale's apps. Wiremu had built React front ends for years at a web agency, and he expected model-driven apps to feel like a strange, restricted version of the same thing. By the end of the first session he had changed his mind. "It is not a restricted web app," he said. "It is a host that lets me plug in at very particular points, and it keeps its promises if I keep mine."

Maribeth Ferreira-Quon, the registrar champion, came to most sessions, because her Transcript Office app and the facilities apps would be the first to receive any new client code. Kwabena Asante-Lowe joined when a change would affect reporting, and Rupert Ellingsworth, who governs Lumenvale's environments, dropped in whenever code was about to leave a developer environment. Everything in this course was built first in Wiremu Dev, his developer environment, inside solutions with the publisher prefix lcc.

Where client scripting fits

Model-driven apps let makers do a great deal without code. Business rules can show, hide, require and lock columns, set values and show messages. Forms can be arranged by drag and drop, and views can be filtered and sorted. Client scripting is the next step: JavaScript that runs in the browser when something happens in a form, a grid or a command, and that can do things no setting does. Typical uses are reading and writing several columns at once based on a calculation, showing or hiding whole sections or tabs, filtering a lookup based on another value, calling the Dataverse Web API to fetch related data, opening a dialog or a custom page, and warning the user before a risky save.

Client scripting has one firm limit, covered in MSBA-270: it runs only in the app where it is added, and only when a person is using that app. A rule that must hold for every change, whether it comes from a form, a canvas app, an import, a flow or another system, belongs on the server, in a plug-in or in a Dataverse feature. Client code improves the experience: it can stop a person from making an obvious mistake, guide them, and save them work. It is not a security boundary. Anyone with the right privileges can change the same row through the Web API without running a line of it.

Configuration first; client script where it earns its place.
NeedFirst choiceWhen client script is justified
Make a column required or read-only on a conditionBusiness ruleThe condition needs data the rule cannot see, such as related rows
Show or hide a whole section or tabSeparate forms or tabsThe section must change as the user edits the row
Filter a lookup by another valueRelated records filtering on the lookupThe filter is more complex than one relationship
Fetch and show related dataQuick view form or subgridThe data must be combined, calculated or shown in a message
Stop a save that breaks a ruleServer-side plug-in or business rule with table scopeOnly as an early warning, in addition to the server check

Signe had a simple test, which she repeated whenever Wiremu proposed a script. "If I delete this script tomorrow, what breaks?" If the answer was "the data becomes wrong", the logic was in the wrong place. If the answer was "the form becomes harder to use", client script was a reasonable home for it.

Web resources and libraries

JavaScript reaches a model-driven app as a web resource, a file stored in Dataverse and carried in solutions like any other component. A web resource has a name that starts with the publisher prefix and usually looks like a path, for example lcc_/scripts/workorder.js. The path-like name keeps related files together and makes relative references work, but it is only a name: Dataverse does not store real folders.

A form uses a script by adding the web resource as a form library and then registering one or more event handlers: the name of a function in that library and the event that should call it. A form can have several libraries, and their order matters only if one depends on another. Libraries are loaded when the form opens, so a large library slows every load. Lumenvale's rule was one library per table, plus a small shared library of helpers, and no third-party framework loaded into forms unless a review agreed it was worth the weight.

Three boxes in a row joined by arrows: a web resource named lcc_/scripts/workorder.js, the form library that adds it to the work order form, and an event handler that calls the function Lumenvale.WorkOrder.onLoad. Notes say the web resource is in a solution with the publisher prefix lcc and that the execution context is passed as the first parameter.
From file to form: web resource, form library, event handler.

Namespaces and the shape of a library

Every script added to a form shares the page with Microsoft's own scripts and with every other library on the form. A function declared at the top level of a file becomes a global name, and two libraries that both declare a function called onLoad will quietly overwrite each other. The answer is a namespace: one global object per organization, with an object per table inside it, and functions inside those. At Lumenvale the convention was Lumenvale.WorkOrder, Lumenvale.Transcript and so on.

A namespaced form library. The choice value, tab and section names are examples; read your own from the form and table definitions.
var Lumenvale = window.Lumenvale || {};
Lumenvale.WorkOrder = (function () {
    "use strict";

    function onLoad(executionContext) {
        var formContext = executionContext.getFormContext();
        toggleContractorSection(formContext);
        formContext.getAttribute("lcc_category").addOnChange(onCategoryChange);
    }

    function onCategoryChange(executionContext) {
        toggleContractorSection(executionContext.getFormContext());
    }

    function toggleContractorSection(formContext) {
        var category = formContext.getAttribute("lcc_category").getValue();
        var external = (category === 100000003); // example choice value for External
        formContext.ui.tabs.get("tab_general").sections.get("sec_contractor").setVisible(external);
    }

    return { onLoad: onLoad, onCategoryChange: onCategoryChange };
}());

Three habits in that small file are worth copying. The library exposes only the functions that the form calls, and keeps helpers private inside the function wrapper. It never touches the page's HTML directly; everything goes through the Client API, because Microsoft changes the page's markup without notice and supports only the documented objects. And it uses logical names, such as lcc_category, which do not change when a maker renames a column's display name.

The Client API object model

The Client API is the set of objects and methods Microsoft supports for scripts in model-driven apps. Code written against it keeps working as the app's interface changes; code that reaches into the page's markup, or uses undocumented internal functions, breaks without warning and is not supported. The model has a small number of root objects, and learning which one to reach for is most of the battle.

A diagram of the Client API. The execution context passed to a handler leads to the form context, with data and ui, and to the grid context for subgrid rows. The form context leads to attributes, which hold values, and to controls, tabs and sections. A separate panel labelled Xrm lists Xrm.WebApi, Xrm.Navigation, Xrm.Utility, Xrm.App, Xrm.Device, and Xrm.Encoding and Xrm.Panel.
The Client API: context objects passed to handlers, and the global Xrm namespaces.
The root objects of the Client API.
ObjectWhat it gives youHow you get it
Execution contextThe event that is running, shared variables between handlers, and the form or grid contextPassed to the handler as its first parameter when the option is selected
Form contextThe form's data (formContext.data) and user interface (formContext.ui), attributes and controlsexecutionContext.getFormContext()
Grid contextA subgrid or editable grid: its rows, refresh and eventsformContext.getControl("subgrid_name") on a form, or from the execution context in a grid event
XrmGlobal namespaces such as Xrm.WebApi and Xrm.Navigation that do not depend on one formAvailable globally in the app

The distinction between attributes and controls confuses almost everyone at first. An attribute is the data: the value of a column for the open row, whether it is required, whether it has changed. A control is one place on the form where an attribute is shown. One attribute can appear in several controls, for example on two tabs, or in the header and the body. Setting a value works on the attribute; hiding, disabling or putting a notification next to a field works on the control. So formContext.getAttribute("lcc_priority").setValue(1) changes the data, while formContext.getControl("lcc_priority").setVisible(false) hides one appearance of it.

Why Xrm.Page is gone

Older samples on the internet use Xrm.Page to reach the form, as in Xrm.Page.getAttribute("name"). Microsoft deprecated Xrm.Page years ago in favour of the form context passed through the execution context, and it is not part of new development. The reason is practical. A model-driven app can show more than one form context at once: a main form and a quick create form, or a form opened in a side pane next to another form. A global Xrm.Page cannot say which one it means. The execution context always belongs to the event that called the handler, so formContext is unambiguous. Solution checker flags Xrm.Page, and Lumenvale's pull request template asked reviewers to reject it.

Wiremu found an old script in the registrar environment, written years earlier by a contractor, that used Xrm.Page throughout and called internal functions on the page. It still worked on the main form but failed silently when the same table was opened in a side pane. Rewriting it to use the execution context took an afternoon and fixed the side-pane problem without any other change.

Calling Dataverse from script: Xrm.WebApi

Client scripts often need data that is not on the form: the number of open work orders for a room, the account manager of a related account, the hold status on a student record. Xrm.WebApi wraps the Dataverse Web API for exactly this. Its methods return promises, so they work naturally with async and await, and they run as the signed-in user, so security roles still apply. A script cannot read what the user cannot read.

The main Xrm.WebApi methods.
MethodUse
Xrm.WebApi.retrieveRecordRead one row by its ID, with a $select and optional $expand query
Xrm.WebApi.retrieveMultipleRecordsRead many rows with an OData query or FetchXML, with a maximum page size and paging through the next link
Xrm.WebApi.createRecord, updateRecord, deleteRecordCreate, change or delete one row
Xrm.WebApi.execute and executeMultipleRun a request object: actions, functions, custom APIs, and operations such as Associate and Disassociate
Xrm.WebApi.online and Xrm.WebApi.offlineTarget the server or the offline store on mobile; the plain methods choose automatically
Reading rows with paging. For counts in production, a FetchXML aggregate or a rollup column is usually cheaper than reading every row.
async function countOpenJobsForRoom(roomId) {
    var query = "?$select=lcc_workorderid" +
        "&$filter=_lcc_room_value eq " + roomId + " and statecode eq 0";
    var result = await Xrm.WebApi.retrieveMultipleRecords("lcc_workorder", query, 50);
    var count = result.entities.length;
    var next = result.nextLink;
    while (next) {
        // read the next page using the paging cookie in nextLink
        result = await Xrm.WebApi.retrieveMultipleRecords("lcc_workorder", "?" + next.split("?")[1], 50);
        count += result.entities.length;
        next = result.nextLink;
    }
    return count;
}

Two points from this example come up on the exam and in real reviews. First, retrieveMultipleRecords returns at most the page size requested, and a nextLink property when more rows exist; code that ignores nextLink silently works with partial data. Second, every call is a network round trip from the user's browser. A script that makes ten calls on load makes the form slow on a weak connection, which at Lumenvale meant every technician in a boiler room. Signe's rule was to fetch only the columns needed, combine requests where possible, and never call the Web API in a loop that runs once per row on a grid.

Associate and Disassociate, which link and unlink rows in a many-to-many relationship, do not have their own Xrm.WebApi methods. They are sent through Xrm.WebApi.execute with a request object that describes the operation, the target and the related rows. The same execute method runs Dataverse actions, functions and custom APIs, so the Calculate Transcript Fee custom API that Signe designed in MSBA-270 could be called from a form script to show the fee before the officer saves.

Worked problem

Choosing between a business rule and a script

Delphine Okoro-Vance, the business owner of the facilities work order solution, asks for three changes on the work order form: make the Due Date required when Priority is Urgent; show the Contractor section only when Category is External; and warn the dispatcher if the selected room already has three or more open jobs. Which need script?

Show solution
  1. Making a column required on a condition is exactly what a business rule does, and a business rule with table scope would also apply in other forms. No script is needed.
  2. Business rules can show and hide columns but not sections. Showing a whole section based on Category needs a form script, or a different design such as a separate tab for external jobs. A small script is reasonable.
  3. Counting open jobs for a room needs data that is not on the form. A business rule cannot query other rows, so a script that calls Xrm.WebApi and shows a form notification is justified. It is a warning, not a block, so client side is the right place.

Answer: Only the second and third changes need script. The first is a business rule, which is cheaper to maintain and applies more widely.

Writing scripts that survive

Model-driven apps update every few weeks. Scripts that follow the Client API keep working; scripts that take shortcuts break at the worst moment. Signe's checklist for every library Wiremu wrote was short. Use the execution context and never Xrm.Page. Use logical names, not labels. Check for null before using a value, because an empty lookup returns null and a new row has no ID. Do not assume a control exists, because a maker can remove a field from a form; check the control before calling methods on it. Avoid synchronous network calls, which block the browser and are flagged by solution checker. And keep the library small.

Wiremu added one habit of his own from web work: a version string at the top of every library and a line written to the console with that version when the form loads in a developer environment. When a tester reported a problem, the first question was always which version they had, and the browser could answer it without guessing about caches.

Common mistakes

  • MistakeUsing Xrm.Page to reach the form.

    InsteadPass the execution context to the handler and call getFormContext(); Xrm.Page is deprecated and ambiguous when several forms are open.

  • MistakeDeclaring functions at the top level of a library.

    InsteadPut everything inside one organization namespace so libraries cannot overwrite each other.

  • MistakeReaching into the page's HTML with document.getElementById.

    InsteadUse only documented Client API objects; the page's markup changes without notice.

  • MistakeTreating a client-side check as enforcement.

    InsteadKeep rules that must always hold on the server; client script is a helper for people using one app.

  • MistakeIgnoring nextLink from retrieveMultipleRecords.

    InsteadFollow nextLink, or design the query so that one page is enough.

At the end of the session Wiremu rewrote the old contractor script in Wiremu Dev and ran solution checker on it. The report that had listed eleven issues listed none. Maribeth asked whether her transcript form would look any different. "Not at all," Signe said. "That is the point. Now it will still look the same next year."

Summary and key terms

  • Client scripting adds JavaScript to model-driven forms, grids and commands to improve the experience where configuration cannot; it is not a way to enforce rules.
  • Scripts are web resources added to forms as libraries, with event handlers naming functions and events; namespaces keep libraries from colliding.
  • The Client API is the supported object model: the execution context, the form context with data and ui, the grid context, and the global Xrm namespaces.
  • Attributes hold data and controls show it; one attribute can have several controls.
  • Xrm.Page is deprecated; always use the form context from the execution context.
  • Xrm.WebApi reads and writes Dataverse as the signed-in user; follow nextLink for more pages and use execute for actions, custom APIs, Associate and Disassociate.
Web resource
A file such as JavaScript, HTML or an image stored in Dataverse and carried in solutions.
Form library
A JavaScript web resource added to a form so that its functions can be called by event handlers.
Execution context
The object the platform passes to a handler, describing the event and giving access to the form or grid context.
Form context
The object that represents an open form, with its data and user interface.
Attribute
In the Client API, the data for one column of the open row.
Control
In the Client API, one place on the form where an attribute is shown.
Xrm.WebApi
The Client API namespace for creating, reading, updating and deleting Dataverse rows and running requests from script.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why is Xrm.Page unsuitable for new scripts?

    Show answer

    It is deprecated and global, so it cannot tell which form is meant when several are open; the form context from the execution context always belongs to the event that called the handler.

  2. What is the difference between getAttribute and getControl?

    Show answer

    getAttribute returns the data for a column; getControl returns one place where it is shown on the form. Values are set on attributes; visibility and notifications are set on controls.

  3. How do you link two rows in a many-to-many relationship from script?

    Show answer

    Send an Associate request through Xrm.WebApi.execute; there is no dedicated method for it.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz