Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

Sample JavaScripts for Dynamics 365 CE or DataVerse Power APps

Sample JavaScripts for Dynamics 365 CE or DataVerse Power APps

Dynamically Add event handlers in Dynamics 365 Form Scripts.

//Using namespace in JavaScript Code
var MyJS = MyJS || {};
MyJS.GetCustomer = function (firstname, lastname) {
    };
MyJS.GetRecordInfo = function () {
    };
 
// Code to run in the form OnLoad event
MyJS.formOnLoad = function (executionContext) {
var formContext = executionContext.getFormContext();
  
 // Code to run in the column OnChange event
MyJS.attributeOnChange = function (executionContext) {
var formContext = executionContext.getFormContext();
}
 
  // Code to run in the form OnSave event
MyJS.formOnSave = function (executionContext) {
var formContext = executionContext.getFormContext();
}  
}

// get lookup
var customer = formContext.getAttribute("customerid").getValue();
var customerEntityType = customer[0].entityType;
var customerId = customer[0].id;
var customerName = customer[0].name;

//getvalue
var title = formContext.getAttribute("fieldname").getValue();
// Get choice text
var casetype=formContext.getAttribute("fieldname").getText();

//set value
// Set lookup value
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = "e4436b-4cd6-ec11-a7b5-000d3a9c27d2";
lookupValue[0].entityType = "contact";
lookupValue[0].name = "Test name";
formContext.getAttribute("customerid").setValue(lookupValue);

// Set choices values
formContext.getAttribute("degree").setValue([100000000,100000001]);

// Set text value
formContext.getAttribute("textfield").setValue("Those are the steps");

// Set number value
formContext.getAttribute("numberfield").setValue(100);

//Get current row data
var currentRow = formContext.data.entity.getEntityReference();
var currentRowEntityType = currentRow.entityType;
var currentRowId = currentRow.id;
var currentRowId2 = currentRow.id.replace(/{|}/g, '');
var currentRowName = currentRow.name;

//Read value from related record

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
}
);

//show hide field
formContext.getControl("caseorigincode").setVisible(true);
formContext.getControl("caseorigincode").setVisible(false);

//show hide section
// 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);

//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);

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

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

//set all fields in a section readonly
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
disableSection(formContext,"Summary","Case Details Summary");

//set all fields in a tab readonly
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
disableTab(formContext,"Summary");

//bpf fields in JS
// 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);

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

//alert dialog and confirm 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.");
});

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

//create record
// define the data to create new account
var data =
    {
        "name": "Sample Account",
        "creditonhold": false,
        "address1_latitude": 47.639583,
        "description": "This is the description of the sample account",
        "revenue": 5000000,
        "accountcategorycode": 1
    }

// create account record
Xrm.WebApi.createRecord("account", data).then(
    function success(result) {
        console.log("Account created with ID: " + result.id);
        // perform operations on record creation
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    }
);

//update record
// define the data to update a record
var data =
    {
        "name": "Updated Sample Account ",
        "creditonhold": true,
        "address1_latitude": 47.639583,
        "description": "This is the updated description of the sample account",
        "revenue": 6000000,
        "accountcategorycode": 2
    }
// update the record
Xrm.WebApi.updateRecord("account", "5531d753-95af-e711-a94e-000d3a11e605", data).then(
    function success(result) {
        console.log("Account updated");
        // perform operations on record update
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    }
);

//delete record
Xrm.WebApi.deleteRecord("account", "5531d753-95af-e711-a94e-000d3a11e605").then(
    function success(result) {
        console.log("Account deleted");
        // perform operations on record deletion
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    }
);


Take a look of all code : https://docs.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/xrm-webapi

https://docs.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference

Hope this helps

You can enroll now !We are giving 30% discount on our Internship Program

Don’t miss the chance to participate in the upcoming Internship Program which will be done using Microsoft Dot Net Web Development Full Stack Technology. The new batch will be starting from May 20, 2024.  We will have most experienced trainers for you to successfully complete the internship with live project experience.

Why to choose Our Internship Program?

Industry-Relevant Projects
Tailored Assignments: We offer projects that align with your academic background and career aspirations.
Real-World Challenges: Tackle industry-specific problems and contribute to meaningful projects that make a difference.

Professional Mentorship
Guidance from Experts: Benefit from one-on-one mentorship from seasoned professionals in your field.
Career Development Workshops: Participate in workshops that focus on resume building, interview skills, and career planning.

Networking Opportunities
Connect with Industry Leaders: Build relationships with professionals and expand your professional network.
Peer Interaction: Collaborate with fellow interns and exchange ideas, fostering a supportive and collaborative environment.

Skill Enhancement
Hands-On Experience: Gain practical skills and learn new technologies through project-based learning.
Soft Skills Development: Enhance communication, teamwork, and problem-solving skills essential for career success.

Free Demo Class Available