Power AppsBeginner
Xrm.WebApi form script basics
Read and update related records from a model-driven form using Xrm.WebApi, with async/await and proper error handling.
What you'll learn
- Register a form OnLoad handler with execution context
- Read related records with Xrm.WebApi
- Avoid the lookup ID curly-brace trap
Form scripts are still the quickest way to add smart behaviour to a model-driven app. Xrm.WebApi gives you promise-based access to Dataverse without building URLs by hand.
Register the handler
Add your web resource to the form, then register Unplugged.Account.onLoad on the OnLoad event and tick Pass execution context.
Read a related record
var Unplugged = Unplugged || {};
Unplugged.Account = {
onLoad: async function (executionContext) {
const formContext = executionContext.getFormContext();
const contact = formContext.getAttribute("primarycontactid").getValue();
if (!contact) return;
try {
const id = contact[0].id.replace(/[{}]/g, "");
const result = await Xrm.WebApi.retrieveRecord("contact", id, "?$select=emailaddress1,jobtitle");
formContext.ui.setFormNotification(
`Primary contact: ${result.jobtitle ?? "No job title"} · ${result.emailaddress1 ?? "no email"}`,
"INFO",
"primary-contact"
);
} catch (e) {
console.error(e);
}
},
};Keep it maintainable
- Use a namespace object so functions don't clash with other scripts.
- Use
$selectto fetch only the columns you need. - Prefer business rules for simple show/hide logic, and save JavaScript for what they can't do.
J / K next or previous article