Walkthrough: Write your first client script in model-driven apps - Power Apps | Microsoft Learn
模型驱动必须学会的功能:
// A namespace defined for the sample code
// As a best practice, you should always define
// a unique namespace for your libraries
var Example = window.Example || {};
(function () {
// Define some global variables
var myUniqueId = "_myUniqueId"; // Define an ID for the notification
var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName; // get current user name
var currentUserId = Xrm.Utility.getGlobalContext().userSettings.userId;
var uniqueName = Xrm.Utility.getGlobalContext().organizationSettings.organizationId;
var message = currentUserName + ": Your JavaScript code in action!";
var currentDate = new Date();
// Code to run in the form OnLoad event
this.formOnLoad = function (executionContext) {
var formContext = executionContext.getFormContext();
formContext.getAttribute("crd18_requestor").setValue(currentUserId);
formContext.getAttribute("crd18_company").setValue(uniqueName);
formContext.getAttribute("crd18_requestor_name").setValue(currentUserName);
formContext.getAttribute("crd18_request_date").setValue(currentDate.toLocaleDateString());
formContext.getAttribute("crd18_request_status").setValue(currentDate.toLocaleDateString());
// Display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function () { formContext.ui.clearFormNotification(myUniqueId); }, 5000);
}
// Code to run in the column OnChange event
this.attributeOnChange = function (executionContext) {
var formContext = executionContext.getFormContext();
// Automatically set some column values if the account name contains "Contoso"
var accountName = formContext.getAttribute("name").getValue();
if (accountName.toLowerCase().search("contoso") != -1) {
formContext.getAttribute("websiteurl").setValue("https://www.contoso.com");
formContext.getAttribute("telephone1").setValue("425-555-0100");
formContext.getAttribute("description").setValue("Website URL, Phone and Description set using custom script.");
}
}
// Code to run in the form OnSave event
this.formOnSave = function () {
// Display an alert dialog
Xrm.Navigation.openAlertDialog({ text: "Record saved." });
}
}).call(Example);