Search This Blog

Sunday, February 9, 2025

The most used JavaScript Methods for Dynamics CRM v9.x

 Most of the examples are provided as functions that you can easily test in the On Load and On Save by generating form Context from execution Context.

============================================================
//Execute all On Load events here

function OnLoad(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Sample code for On Load Event
Xrm.Utility.alertDialog("This is an alert for On Load Event.");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Execute all OnSave events here

function OnSave(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Sample code for On Save Event
Xrm.Utility.alertDialog("This is an alert for On Save Event.");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Execute Field on Change events here, This could be specific to each field

function OnChange(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Sample code for On Change Event
Xrm.Utility.alertDialog("This is an alert for On Change Event.");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get Lookup ID

function GetLookupId(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get lookup ID here, Give lookup field logical name here
var lookupId = formContext.getAttribute("new_organizationid").getValue()[0].id;
Xrm.Utility.alertDialog(lookupId);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get Lookup Name

function GetLookupName(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get lookup name here, Give lookup field logical name here
var lookupName = formContext.getAttribute("new_organizationid").getValue()[0].name;
Xrm.Utility.alertDialog(lookupName);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Entity Logical Name

function GetEntityLogicalName(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get entity logical name here, Give lookup field logical name here
var entityName = formContext.getAttribute("new_organizationid").getValue()[0].entityType;
Xrm.Utility.alertDialog(entityName);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the text value from Filed

function GetTextValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get text value of the field here, Give field logical name here
var textValue = formContext.getAttribute("new_employeebusinessid").getValue();
Xrm.Utility.alertDialog(textValue);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Data base value from Option Set Field

function GetOptionSetDataBaseValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get data base value of the option set field here, Give field logical name here
var databaseValue = formContext.getAttribute("new_gender").getValue();
Xrm.Utility.alertDialog(databaseValue);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Option Set text value

function GetOptionSetTextValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get text value of the option set field here, Give field logical name here
var optionSetTextValue = formContext.getAttribute("new_gender").getText();
Xrm.Utility.alertDialog(optionSetTextValue);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Data base value from Two Option Set Field

function GetTwoOptionSetDataBaseValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the value of the two option set field here, Give field logical name here
var databaseValue = formContext.getAttribute("new_type").getValue();
Xrm.Utility.alertDialog(databaseValue);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Date Field Value

function GetDateFieldValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Getvalue of the field here, Give field logical name here
var dateOfBirth = formContext.getAttribute("new_dateofbirth").getValue();
Xrm.Utility.alertDialog(dateOfBirth);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Date, Month, Year from Date Field Value

function GetDateFieldValues(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get value of the field here, Give field logical name here
var dateOfBirth = formContext.getAttribute("new_dateofbirth").getValue();
//Get Year
Xrm.Utility.alertDialog(dateOfBirth.getFullYear());
//Get Month
Xrm.Utility.alertDialog(dateOfBirth.getMonth());
//Get Date(Day)
Xrm.Utility.alertDialog(dateOfBirth.getDate());
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the text value to Text Field

function SetTextFieldValue(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set the field value here
formContext.getAttribute("new_employeebusinessid").setValue("abcd");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the Data base value to Option Set Field

function SetOptionSetDataBaseValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set the field value here
formContext.getAttribute("new_gender").setValue(123456);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the Data base value to Two Option Set Field

function SetTwoOptionSetDataBaseValue(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set the field value here - true
formContext.getAttribute("new_type").setValue(true);
//Set the field value here - false
formContext.getAttribute("new_type").setValue(false);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the Date Field Value

function SetDateFieldValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the current Date
var dateOfBirth = new Date();
//Set the Current Date to date field
formContext.getAttribute("new_dateofbirth").setValue(dateOfBirth);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the Lookup Field Value

function SetLookUpFieldValue(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var lookupValue = new Array();
var lookupValue[0]= new Object();
lookupValue[0].id = "919F28C4-F9BB-E911-A977-000D3AF04F8C";//Guid of the Record to be set
lookupValue[0].name = "Tata Consultancy Services"; //Name of the record to be set
lookupValue[0].entityType = "new_organization" //Entity Logical Name
formContext.getAttribute("new_organizationid").setValue(lookupValue);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set the Field Requirement Level

function SetTheFieldRequirementLevel(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set as Business Required
formContext.getAttribute("new_dateofbirth").setRequiredLevel("required");
//Set as Buiness Recommended
formContext.getAttribute("new_dateofbirth").setRequiredLevel("recommended");
//Set as Optional
formContext.getAttribute("new_dateofbirth").setRequiredLevel("none");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Enable or Disable Field (Lock/Unlock)

function SetTheFieldState(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set field as Read only
formContext.getAttribute("new_dateofbirth").setDisabled(true);
//Set field as Editable
formContext.getAttribute("new_dateofbirth").setDisabled(false);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Apply Lookup Filter

function ApplyLookUpFilter(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the custom filter
var filter = "";
//Get the lookup field
var lookupField = formContext.getAttribute("new_organizationid");

//Apply custom Filter for lookup
lookupField.addPreSearch(function () {
lookupField.addCustomFilter(filter);
});
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Show Hide Fields

function ShowHideFields(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Show Field
formContext.getAttribute("new_dateofbirth").setVisible(true);
//Hide Field
formContext.getAttribute("new_dateofbirth").setVisible(false);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Show or Hide Navigation Items

function ShowHideNavigationItems(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Show Organizations
formContext.ui.navigation.items.get("organizations").setVisible(true);
//Hide Organizations
formContext.ui.navigation.items.get("organizations").setVisible(false);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Set Form Notification

function SetFormNotification(executionContext){
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Set Form Notification
formContext.ui.setFormNotification("This is a MS DYNAMICS CRM Form Notification", "INFO", "1");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Clear Form Notification

function ClearFormNotification(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Clear Form Notification
formContext.ui.clearFormNotification("This is a MS DYNAMICS CRM Form Notification", "INFO", "1");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Show Progress Indicator

function ShowProgressIndicator() {
try {
Xrm.Utility.showProgressIndicator("The Page is Loading... Please wait...");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Clear Progress Indicator

function ClearProgressIndicator() {
try {
Xrm.Utility.closeProgressIndicator();
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Show Hide Tabs based on field values

function ShowHideTabs(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var isProcessed = formContext.getAttribute("progres_isprocessed").getValue(); //Two Option set field
var generalTab = formContext.ui.tabs.get("GENERAL"); //Get Tab
if (isProcessed === false) {
generalTab.setVisible(false); //Hide Tab
} else {
generalTab.setVisible(true); //Show Tab
}
formContext.ui.tabs.get("CASH_PLAN_FLOW_DETAILS").setDisplayState("collapsed"); //Collapse Tab
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Show Hide Sections based on field values

function ShowHideSections(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var isProcessed = formContext.getAttribute("progres_isprocessed").getValue(); //Two Option set field
var generalTab = formContext.ui.tabs.get("GENERAL"); //Get Tab
var asstPackages = generalTab.sections.get("ASSISTANCE_PACKAGES"); //Get sections
var payments = generalTab.sections.get("PAYMENT_RECORDS"); //Get sections
if (isProcessed === false) {
asstPackages.setVisible(true); //Show Section
payments.setVisible(false); //Hide Section
} else {
asstPackages.setVisible(false); //Show Section
payments.setVisible(true); //Show Section
}
formContext.ui.tabs.get("CASH_PLAN_FLOW_DETAILS").setDisplayState("collapsed"); //Collapse Tab
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Save Form

function SaveForm(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Save Form
formContext.data.entity.save();
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Save Form and Close Record

function SaveFormAndClose(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Save Form and Close
formContext.data.entity.save("saveandclose");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Save Form and Open Create Form

function SaveFormAndOpenCreateForm(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Save Form and Close
formContext.data.entity.save("saveandnew");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Close Form

function CloseForm(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Close Form
formContext.ui.close();
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Save the data on Read Only Field

function ForceSaveDataOnReadOnlyField(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Save forcefully
formContext.getAttribute("new_employeetype").setSubmitMode("always");
//Save forcefully
formContext.getAttribute("new_employeetype").setSubmitMode("never");
//Save forcefully
formContext.getAttribute("new_employeetype").setSubmitMode("dirty");
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get Dirty Fields from Form

function GetFormDirtyFields(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var attributes = formContext.data.entity.attributes.get()
for (var i in attributes) {
var attribute = attributes[i];
if (attribute.getIsDirty()) {
Xrm.Utility.alertDialog("Attribute dirty: " + attribute.getName());
}
}
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get Form Type

function GetFormType(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get Form Type
var formType = formContext.ui.getFormType();
Xrm.Utility.alertDialog(formType);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get GUID of the Current Record

function GetGuidOfTheRecord(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the current Record Guid
var recordGuid = formContext.data.entity.getId();
Xrm.Utility.alertDialog(recordGuid);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get GUID of the Current User

function GetGuidOfTheRecord(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the Current User Guid
var userGuid = formContext.context.getUserId();
Xrm.Utility.alertDialog(userGuid);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Security Roles of Current User

function GetSecurityRolesOfCurrentUser(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the Current User Guid
var userRoles = formContext.context.getUserRoles();
Xrm.Utility.alertDialog(userRoles);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the CRM Clinet Url

function GetTheCRMClientUrl(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the Client Url
var clientUrl = formContext.context.getClientUrl();
Xrm.Utility.alertDialog(clientUrl);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the User Language ID

function GetTheUserLanguageID(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the Current User Language ID
var userLanguage = formContext.context.getUserLcid();
Xrm.Utility.alertDialog(userLanguage);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Get the Current User Name

function GetTheCurrentUserName(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
//Get the Current User Name
var userName = formContext.context.userSettings.userName;
Xrm.Utility.alertDialog(userName);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Create Record using Xrm.WebApi

function CreateRecord() {
try {
var entityName = "new_organization"; //Entity Logical Name
//Data used to Create record
var data = {
"new_organizationname": "Tata Consultancy Services",
"new_description": "This is the description of Tata Consultancy Services",
"new_noofemployees": 400000,
"new_revenue": 20000000
}
Xrm.WebApi.createRecord(entityName, data).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Update Record using Xrm.WebApi

function UpdateRecord() {
try {
var entityName = "new_organization"; //Entity Logical Name
var recordId = "919F28C4-F9BB-E911-A977-000D3AF04F8C"; //Guid of the Record
//Data used to Create record
var data = {
"new_organizationname": "Tata Consultancy Services",
"new_description": "This is the description of Tata Consultancy Services",
"new_noofemployees": 450000,
"new_revenue": 30000000
}
Xrm.WebApi.updateRecord(entityName, recordId, data).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Delete Record using Xrm.WebApi

function DeleteRecord() {
try {
var entityName = "new_organization"; //Entity Logical Name
var recordId = "919F28C4-F9BB-E911-A977-000D3AF04F8C"; //Guid of the Record
Xrm.WebApi.deleteRecord(entityName, recordId).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Retrieve Record using Xrm.WebApi

function RetrieveRecord() {
try {
var entityName = "new_organization"; //Entity Logical Name
var recordId = "919F28C4-F9BB-E911-A977-000D3AF04F8C"; //Guid of the Record
var columnsToRetrieve = "$select=new_organizationname, new_noofemployees, new_revenue"; //Columns to Retrieve
Xrm.WebApi.retrieveRecord(entityName, recordId, columnsToRetrieve).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Retrieve Multiple Record using Xrm.WebApi

function RetrieveMultipleRecords() {
try {
var entityName = "new_organization"; //Entity Logical Name
var query = "?$select=new_organizationname, new_noofemployees, new_revenue&$top=3"; //Columns to Retrieve
Xrm.WebApi.retrieveMultipleRecords(entityName, query).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Call Asynchronous Action

function CallAsynchronousAction(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var webApiVersionNumber = "v9.1";
var serverURL = formContext.context.getClientUrl() + "/api/data/" + webApiVersionNumber + "/";;
var actionName = "new_customaction"; //Action name
var data = {}; //Action Parameters
if (typeof (data) === "undefined") {
data = {};
}
var oDataEndPoint = serverURL+ actionName;
var req = new XMLHttpRequest();
req.open("POST", oDataEndPoint, true); //Action will be invoked Asynchronously
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204 || this.status === 200) {
if (this.statusText === "No Content" || this.statusText === "") // In case of 204
var response = req.response;
else {
var response = JSON.parse(req.response);
}
} else {
var error = JSON.parse(req.response).error;
Xrm.Utility.alertDialog(error.message);
}
}
};
req.send(JSON.stringify(data));
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Call Synchronous Action

function CallSynchronousAction(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var webApiVersionNumber = "v9.1";
var serverURL = formContext.context.getClientUrl() + "/api/data/" + webApiVersionNumber + "/";;
var actionName = "new_customaction"; //Action name
var data = {}; //Action Parameters
if (typeof (data) === "undefined") {
data = {};
}
var oDataEndPoint = serverURL + actionName;
var req = new XMLHttpRequest();
req.open("POST", oDataEndPoint, false); //Action will be invoked synchronously
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204 || this.status === 200) {
if (this.statusText === "No Content" || this.statusText === "") // In case of 204
var response = req.response;
else {
var response = JSON.parse(req.response);
}
} else {
var error = JSON.parse(req.response).error;
Xrm.Utility.alertDialog(error.message);
}
}
};
req.send(JSON.stringify(data));
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

//Associate request using Web Api

function AssociateRequest(executionContext) {
try {
//Get the form context
var formContext = executionContext.getFormContext();
var serverURL = formContext.context.getClientUrl();
var currentEntityPlurarName = "fieldsecurityprofiles";
var currentEntityId = "4E7C654C-7150-E711-811F-C4346BACBA84";//Get Field Security Profile id
var relationShipName = "systemuserprofiles_association";
var otherEntityPlurarName = "systemusers";
var otherEntityId = "2F5FC0F6-F247-E811-810F-C4346BDCF131"; //Get System User id
var associate = {}
associate["@odata.id"] = serverURL + "/api/data/v9.1/" + otherEntityPlurarName + "(" + otherEntityId + ")";
var req = new XMLHttpRequest();
req.open("POST", serverURL + "/api/data/v9.1/" + currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref", false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 204) {
//Success
} else {
var error = JSON.parse(this.response).error;
Xrm.Utility.alertDialog(error.message);
}
}
};
req.send(JSON.stringify(associate));
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

Saturday, February 8, 2025

Power Apps – Model Driven Apps/CRM – JavaScript

 1-FORM EVENTS

var Sdk = window.Sdk || {};

(function () {

// Code to run in the form OnLoad event

this.formOnLoad = function (executionContext) {

var formContext = executionContext.getFormContext();

// Add your code from the other tables here

}

// Code to run in the column OnChange event

this.attributeOnChange = function (executionContext) {

var formContext = executionContext.getFormContext();

// Add your code from the other tables here

}

// Code to run in the form OnSave event

this.formOnSave = function (executionContext) {

var formContext = executionContext.getFormContext();

// Add your code from the other tables here

}

}).call(Sdk);

// Add your code from the other tables here

//

2-GET CURRENT ROW DATA

var currentRow = formContext.data.entity.getEntityReference();

// Get row table type ex: “incident” or “account”

var currentRowEntityType = currentRow.entityType;

// Get row GUID ex: “{67e86a65-4cd6-ec11-a7b5-000d3a9c27d2}”

var currentRowId = currentRow.id;

// Get row GUID without brackets ex: “67e86a65-4cd6-ec11-a7b5-000d3a9c…”

var currentRowId2 = currentRow.id.replace(/{|}/g, '');

// Get row logical name ex: “67e86a65-4cd6-ec11-a7b5-000d3a9c27d2”

var currentRowName = currentRow.name;

3-READ VALUES FROM LOOKUP

var customer = formContext.getAttribute("customerid").getValue();
// Get row table type ex: “incident” or “account”
var customerEntityType = customer[0].entityType;
// Get row GUID ex: “{67e86a65-4cd6-ec11-a7b5-000d3a9c27d2}”
var customerId = customer[0].id;
// Get row logical name ex: “67e86a65-4cd6-ec11-a7b5-000d3a9c27d2”
var customerName = customer[0].name;


4-READ VALUES FROM COLUMN

// Get column value
var title = formContext.getAttribute("fieldname").getValue();
// Get choice value
var caseorigin = formContext.getAttribute("fieldname").getValue();
// Get choice text
var caseorigin = formContext.getAttribute("fieldname").getText();

5-SET FIELD VALUES

// Set lookup value
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = "a431636b-4cd6-ec11-a7b5-000d3a9c27d2";
lookupValue[0].entityType = "contact";
lookupValue[0].name = "Nancy Anderson (sample)"
formContext.getAttribute("customerid").setValue(lookupValue);
// Set choices values
formContext.getAttribute("multichoice").setValue([100000000,100000001,100
000002]);
// Set text value
formContext.getAttribute("textfield").setValue("Those are the steps");
// Set number value
formContext.getAttribute("numberfield").setValue(100);

6-READ VALUES FROM RELATED TABLES

// Basic retrieve
Xrm.WebApi.retrieveRecord("contact", customerId,
"?$select=firstname").then(
function success(result) {
console.log("Retrieved values: Name: " + result.firstname);
// perform operations on record retrieval
},
function (error) {
console.log(error.message);
// handle error conditions
}
);
// Using expand
Xrm.WebApi.retrieveRecord("contact", customerId,
"?$select=firstname&$expand=modifiedby($select=fullname;$expand=businessu
nitid($select=name))").then(
function success(result) {
console.log("Name: " + result.modifiedby.fullname);
// perform operations on record retrieval
},
function (error) {
console.log(error.message);
// handle error conditions
}
);


7-SHOW / HIDE FIELDS

//Show
formContext.getControl("caseorigincode").setVisible(true);
//Hide
formContext.getControl("caseorigincode").setVisible(false);

8-SHOW / HIDE SECTIONS

// Show section within a specified tab
var tab = formContext.ui.tabs.get("Summary");
var section = tab.sections.get("Timeline");
section.setVisible(true);
// Hide section within a specified tab
var tab = formContext.ui.tabs.get("Summary");
var section = tab.sections.get("Timeline");
section.setVisible(false);


9-SHOW / HIDE TABS

// Show tab
var tab = formContext.ui.tabs.get("Details");
tab.setVisible(true);
// Hide tab
var tab = formContext.ui.tabs.get("Details");
tab.setVisible(false);


10-SET REQUIRED FIELDS

// Set field as required
formContext.getAttribute("fieldname").setRequiredLevel("required");
// Set field as recommended
formContext.getAttribute("fieldname").setRequiredLevel("recommended");
// Set field as optional
formContext.getAttribute("fieldname").setRequiredLevel("none");

11-SET READ-ONLY FIELDS

// Set field read-only
formContext.getControl("caseorigincode").setDisabled(true);
// Set field editable
formContext.getControl("caseorigincode").setDisabled(false);

12-SET ALL FIELDS READ-ONLY IN SECTION


this.disableSection = function(formContext, tab, section) {
var section = formContext.ui.tabs.get(tab).sections.get(section);
var controls = section.controls.get();
var controlsLenght = controls.length;
for (var i = 0; i < controlsLenght; i++) {
controls[i].setDisabled(true);
}
}
// call the function to disable all the fields in the section
Sdk.disableSection(formContext,"Summary","Case Details Summary");

13-SET ALL FIELDS READ-ONLY IN TAB

this.disableTab = function(formContext, tab) {
formContext.ui.tabs.get(tab).sections.forEach(function (section){
section.controls.forEach(function (control) {
control.setDisabled(true);
})
});
}
// call the function to disable all the fields in the section
Sdk.disableTab(formContext,"Summary");

14-FIELDS IN BPF (Business Process Flow)

// Add "header process_" to the field name
// Set field as required
formContext.getAttribute("header_process_fieldname").setRequiredLevel("re
quired");
// Set field read-only
formContext.getControl("header_process_fieldname").setDisabled(true);

15-REFRESH & SAVE THE FORM

// Save and refresh the form
formContext.data.refresh(true);
// Refresh the form (without saving)
formContext.data.refresh(false);

16-DIALOG

// alert dialog
var alertStrings = { confirmButtonLabel: "Yes", text: "This is an
alert.", title: "Sample title" };
var alertOptions = { height: 120, width: 260 };
Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(
function (success) {
console.log("Alert dialog closed");
},
function (error) {
console.log(error.message);
}
);
// confirm dialog
var confirmStrings = { text:"This is a confirmation.",
title:"Confirmation Dialog" };
var confirmOptions = { height: 200, width: 450 };
Xrm.Navigation.openConfirmDialog(confirmStrings, confirmOptions).then(
function (success) {
if (success.confirmed)
console.log("Dialog closed using OK button.");
else
console.log("Dialog closed using Cancel button or X.");
});

17-SET URL FOR IFRAME

// Set field read-only formContext.getControl("iframe").setSrc(" https://XYZ.com/");

18-Link

https://htmlcheatsheet.com/js/

Monday, January 6, 2025

All things you need to know about Microsoft Power Platforms by PowerApps Mentor

 Overview of Microsoft Power Platform

Microsoft Power Platform is a suite of tools designed to enable businesses to analyze data, automate processes, create custom applications, business websites and build virtual agents. It consists of five main components: Power Apps, Power Pages, Power Automate, Power BI, and Copilot Studio. Each of these tools allows users to create custom applications, automate workflows, and generate insights from data without needing extensive coding skills.

Major Components of Microsoft Power Platform

  1. Power BI:
    • Purpose: Power BI is a business analytics tool that enables users to visualize data and share insights across the organization.
    • Key Features:
      • Data Visualization: Create interactive reports and dashboards.
      • Data Integration: Connects to a wide range of data sources.
      • AI Insights: Uses artificial intelligence to analyze data and provide insights.
      • Collaboration: Share reports and dashboards with colleagues.
  2. Power Apps:
    • Purpose: Power Apps allows users to build custom applications tailored to specific business needs.
    • Key Features:
      • Low-Code Development: Build apps with minimal coding using a drag-and-drop interface.
      • Custom Forms and Views: Design forms and views to capture and display data.
      • Integration: Connects with various data sources and other Microsoft services.
      • Mobile Accessibility: Apps can be used on various devices, including smartphones and tablets.
  3. Power Pages:
    • Purpose: Power Pages (formerly Power Portals) is used to creating business website for organization.
    • Key Features:
      • Low-Code Development: Build websites with minimal coding using a drag-and-drop interface.
      • Integration: Connect only Microsoft Dataverse.
      • Pre-built Templates: Access templates to quickly build common websites.
      • Web/Mobile Accessibility: Website can be used on various devices, including all browsers, smartphones and tablets.
  4. Power Automate:
    • Purpose: Power Automate (formerly Microsoft Flow) is used to automate workflows and tasks across different applications and services.
    • Key Features:
      • Automated Workflows: Create workflows to automate repetitive tasks.
      • Triggers and Actions: Set up triggers and corresponding actions to streamline processes.
      • Pre-built Templates: Access templates to quickly build common workflows.
      • Integration: Works with a wide range of Microsoft and third-party services.
  5. Copilot Studio:
    • Purpose: Copilot Studio (formerly Power Virtual Agents) allows users to create chatbots without needing extensive programming knowledge.
    • Key Features:
      • No-Code Bot Building: Build chatbots using a guided, no-code graphical interface.
      • Integration: Integrates with other Power Platform tools and external services.
      • AI Capabilities: Uses natural language processing to understand and respond to user queries.
      • Deployment: Deploy bots across multiple channels, such as websites, Teams, and more.

Why Use Microsoft Power Platform?

  1. Enhanced Productivity:
    • Streamlined Processes: Automate routine tasks and workflows to free up time for more strategic activities.
    • Quick Solutions: Develop custom applications quickly to address specific business problems without waiting for traditional IT development cycles.
  2. Data-Driven Decisions:
    • Insights and Analytics: Use Power BI to transform raw data into actionable insights, helping in better decision-making.
    • Unified Data: Integrate data from various sources to get a holistic view of business operations.
  3. Improved Collaboration:
    • Sharing and Collaboration: Share reports, dashboards, and apps easily across teams and departments.
    • Communication: Use chatbots created with Power Virtual Agents to provide instant support and information to employees and customers.
  4. Cost Efficiency:
    • Reduced Development Costs: Build and deploy applications with low-code solutions, reducing the need for expensive development resources.
    • Automation Savings: Save time and resources by automating repetitive tasks.

Impact on Your Business

  1. Operational Efficiency:
    • Automated Processes: Power Automate can significantly reduce the time spent on manual, repetitive tasks, leading to increased operational efficiency.
    • Real-Time Data: Power BI provides real-time data analysis, allowing for quicker response times and better management of business operations.
  2. Innovation and Agility:
    • Custom Apps: Power Apps enables the creation of custom applications to address unique business challenges, fostering innovation.
    • Rapid Development: Low-code and no-code tools accelerate the development cycle, allowing businesses to adapt quickly to changing market conditions.
  3. Customer Engagement:
    • Personalized Interactions: Power Virtual Agents can enhance customer service by providing personalized, automated responses to customer inquiries.
    • Better Insights: Analyze customer data with Power BI to gain insights into customer behavior and preferences, enabling more targeted marketing efforts.
  4. Enhanced Decision Making:
    • Data Integration: Integrate data from various sources to provide a comprehensive view of the business, supporting more informed decision-making.
    • Predictive Analytics: Use AI and machine learning capabilities in Power BI to predict trends and outcomes, helping to make proactive business decisions.

Conclusion

Microsoft Power Platform is a powerful suite of tools that empowers businesses to analyze data, automate processes, build custom applications, and create intelligent chatbots. By leveraging these tools, businesses can enhance productivity, improve decision-making, foster innovation, and provide better customer experiences. The integration and ease of use provided by the Power Platform make it a valuable asset for any organization looking to leverage technology to drive business success.


What is a Solution in Power Apps? by PowerApps Mentor

 A Solution in Power Apps is a package or container that groups together various components, such as apps, flows, tables, and resources, into a single manageable unit. Solutions enable you to transport and manage the application and its resources easily across different environments (e.g., from development to production).

Solutions are primarily used in Dataverse-based environments and are important for environments involving Canvas AppsModel-driven Apps, or Power Automate flows that need to be packaged and deployed across multiple environments.

All Types Solutions by PowerApps Mentor

Types of Solutions in Power Apps

  1. Unmanaged Solution:
    • Unmanaged solutions are used during the development process.
    • Changes made to components in an unmanaged solution are directly applied to the system.
    • Unmanaged solutions can be edited and modified freely.
    • Example: If you are working on a new feature in your Project Management App, you would first work in an unmanaged solution while building or modifying components.
  2. Managed Solution:
    • Managed solutions are deployed in production or testing environments.
    • They are typically exported from a development environment as a “managed” package and imported into the production environment.
    • Managed solutions can’t be edited once imported, ensuring that the changes are secure.
    • Example: After completing development on a new feature for your Project Management App, you would export it as a managed solution and import it into the production environment.

All Types of Environment by PowerApps Mentor

What is an Environment in Power Apps?

Environment in Power Apps is like a workspace where you create, manage, and share your apps, data, and other resources. Think of it as a virtual office with its own set of tools and rules, separate from other offices. Each environment can have its own apps, data, and permissions.

Why Are Environments Important?

  1. Organization: Keeps your work organized and separated. For instance, you can have one environment for development and another for production.
  2. Security: Controls who can access and modify resources.
  3. Customization: Allows different setups for different needs, like testing new features in one environment without affecting the live environment.

Types of Environments in Power Apps

Types of Environment in PowerApps
  1. Default Environment
  2. Production Environment
  3. Sandbox Environment
  4. Trial Environment
  5. Developer Environment

1. Default Environment

What is it?

  • Automatically created for each user when they sign up for Power Apps.
  • Everyone in your organization can access it.

2. Production Environment

What is it?

  • Used for running your live apps that users rely on.
  • More controlled and secure than the default environment.

3. Sandbox Environment

What is it?

  • Used for testing and development.
  • You can experiment without affecting the live environment.

4. Trial Environment

What is it?

  • Temporary environment to try out Power Apps and its features.
  • Typically lasts for a limited time (e.g., 30 days).

5. Developer Environment

What is it?

  • Personal environment for individual developers.
  • Comes with the Power Apps Community Plan.
  • Ideal for learning, exploring, and building apps independently.

Conclusion

In Power Apps, environments are essential for organizing, securing, and managing your app development and deployment processes. By understanding and utilizing different types of environments—default, production, sandbox, trial, and developer—you can ensure that your apps are developed, tested, and deployed effectively and securely.

Each environment serves a specific purpose, helping you maintain control over your projects and ensuring that your apps run smoothly in their intended settings.


Right Data Source For Your PowerApps : SharePoint List vs. Dataverse

 Choosing the Right Data Source in PowerApps

When developing applications in PowerApps, selecting the appropriate data source is crucial for ensuring optimal performance, scalability, and functionality. Two of the most common data sources are SharePoint Lists and Dataverse. Both have their strengths and ideal use cases. This guide will help you understand when to use each one.

SharePoint List

SharePoint List is a well-known and widely used data source, particularly within organizations that already utilize SharePoint for collaboration and document management. Here’s when to consider using SharePoint List as your data source:

When to Use SharePoint List

  1. Existing SharePoint Integration:
    • If your organization already heavily relies on SharePoint for document management and collaboration, integrating PowerApps with SharePoint Lists can be seamless.
    • It allows leveraging existing infrastructure and permissions without additional setup.
  2. Simple Data Structures:
    • SharePoint Lists are suitable for simple data structures where complex relationships and transactions are not required.
    • Ideal for lists, task tracking, announcements, contacts, and basic data collection forms.
  3. Small to Medium Data Sets:
    • Best suited for smaller data sets. While SharePoint Lists can handle up to 30 million items, performance can degrade as the volume grows.
    • For applications with a few thousand records, SharePoint Lists provide adequate performance.
  4. Quick Development and Prototyping:
    • Easy to set up and start using, making it great for rapid development and prototyping.
    • Suitable for small-scale applications where speed of deployment is more critical than scalability.
  5. Limited Budget:
    • SharePoint Lists are part of the Office 365 suite, meaning there’s no additional cost for using them if you already have an Office 365 subscription.
    • Ideal for budget-conscious projects where advanced features of Dataverse are not required.

Dataverse

Dataverse (formerly known as the Common Data Service) is a more robust and versatile data platform, offering advanced capabilities for building sophisticated applications. Here’s when to consider using Dataverse as your data source:

When to Use Dataverse

  1. Complex Data Models:
    • Dataverse supports complex data models with relationships, business logic, and workflows.
    • Suitable for applications requiring data integrity, transactional support, and advanced querying capabilities.
  2. Large Data Sets:
    • Designed to handle large volumes of data efficiently.
    • Ideal for enterprise-level applications with hundreds of thousands or millions of records.
  3. Advanced Security and Compliance:
    • Offers advanced security features, including row-level security, field-level security, and integration with Azure Active Directory.
    • Meets high compliance standards, making it suitable for industries with stringent data protection requirements.
  4. Integration and Extensibility:
    • Provides native integration with other Microsoft services like Power Automate, Power BI, and Dynamics 365.
    • Highly extensible, supporting custom connectors and plugins to meet specific business needs.
  5. Business Logic and Automation:
    • Built-in support for business rules, workflows, and automation.
    • Enables the creation of sophisticated business processes and automations directly within the data layer.
  6. Scalability and Performance:
    • Scales efficiently to meet the needs of growing applications.
    • Optimized for performance, ensuring responsive applications even with significant data volumes.

Conclusion

Choosing between SharePoint Lists and Dataverse as your data source in PowerApps depends on several factors, including the complexity of your data, the size of your data sets, security requirements, and integration needs.

  • Use SharePoint List if your application involves simple data structures, smaller data sets, and if you require quick development with minimal setup.
  • Opt for Dataverse when dealing with complex data models, large volumes of data, and advanced security and integration requirements.

By understanding the strengths and limitations of each data source, you can make an informed decision that aligns with your project’s goals and organizational needs.