How to create new Dynamics record using JSCRIPT and WebAPI (with example)
Recently we had the need to allow the system to create a record in Dynamics 365, from another record. And it was decided to use JSCRIPT to enhance the user-experience.
The main reason for this, was that we didn’t want the user to be waiting for a flow to executed or triggered; it had to be a real-time record creation.
Here’s how I did it.
Applies to:
Dynamics 365 On-Prem
Dynamics 365 On-line
Power Platform
Start Building the Script
THIS ARTICLE ASSUMES THAT YOU KNOW HOW TO CREATE A JSCRIPT WEB RESOURCE AND ADD TO THE FORM
In This Example, I will be adding a lookup field to the Opportunity form, asking the user to select a Product. (A lookup on the Products Table). This will be called new_producttoadd
On Change trigger of the Lookup, the JSCRIPT will create and attach a Opportunity Product record to the Opportunity.
NOTE: See the bottom for the complete script.
NOTE2: This script has been cut down to the bear essentials - you may need to add additional code to work in your environment.
Lets start by setting the execution context for this function
function AddProduct(executionContext) {
//--Establish Context Variable
var formContext = executionContext.getFormContext();
Next, we want to ensure that the user has actually selected a product in the lookup and it is not blank
//--Check the user selected a valid product
if (formContext.getAttribute('new_producttoadd').getValue() != null) {
Lets grab some details that we’ll need. Starting with the Product GUID that the user selected
//--Get the product that the user selected
var ProductID = formContext.getAttribute('new_producttoadd').getValue();
var ProductID_ID = ProductID[0].id.replace("}", "").replace("{", "");
and we also need the current record guid of this opportunity
var RecordGUID = formContext.data.entity.getId().replace("}", "").replace("{", "");
Next we need some other information from the user - we need a Quantity if we are to add an Opportunity Product, but we should also default this to 1 to cover our asses. This will be a new field called new_courseqtytoadd
//-- Get the quantity specified by the user and check it is valid. If not, set the value to 1
var ProductQty = 1;
if (formContext.getAttribute("new_courseqtytoadd").getValue() != null) {
ProductQty = formContext.getAttribute("new_courseqtytoadd").getValue();
}
OK. Now we need to build the data object that will be passed to the WebAPI with the basic information for the record.
NOTE: you will need to populate this with data for any required fields otherwise the record creation may fail.
NOTE2: You will see below, for this instance, I have hardcoded the Unit Of Measure (UOM) GUID
var entityLogicalName = "opportunityproduct";
var data = {
"isproductoverridden": false,
"productid@odata.bind": "/products(" + ProductID_ID + ")",
"opportunityid@odata.bind": "/opportunities(" + RecordGUID + ")",
"quantity": parseInt(ProductQty),
"uomid@odata.bind": "/uoms(HARDCODED-GUID)",
"ispriceoverridden": false
}
Next up, we need to create this record. Lets start by kicking off a connection to the WebAPI and sending the two variables from above (the table name and the data object).
We will also specify two resulting functions - one to handle the successful creation and one to handle any failures.
Xrm.WebApi.createRecord(entityLogicalName, data).then(
This is the success function:
function success(result) {
We’re gonna throw the result out to the console log for viewing during troubleshooting
console.log("Record created with ID: " + result.id);
// perform operations on record creation
//add any other post-insert tasks to be done such as clearing fields or resetting the form etc.
},
And the function that will be executed on an error
function (error) {
again, throwing the message to the console helps.
console.log(error.message);
and in this case, Im going to add the error to a text field on the users form so that they can see why it didnt create the record
// handle error conditions
formContext.getControl("new_addskuresponse").setVisible(true);
formContext.getAttribute("new_addskuresponse").setValue(error.message);
}
);
Finally, lets do a quick refresh to load the subgrids
//--Reload the subgrid values
formContext.data.refresh(true);
and close off any curly braces;
}
}
Next up, ensure that the field has an ON CHANGE event to trigger this code and away you go !
Full code from the above article to copy and paste:
function AddProduct(executionContext) {
//--Establish Context Variable
var formContext = executionContext.getFormContext();
//--Check the user selected a valid product
if (formContext.getAttribute('new_producttoadd').getValue() != null) {
//--Get the product that the user selected
var ProductID = formContext.getAttribute('new_producttoadd').getValue();
var ProductID_ID = ProductID[0].id.replace("}", "").replace("{", "");
var RecordGUID = formContext.data.entity.getId().replace("}", "").replace("{", "");
//-- Get the quantity specified by the user and check it is valid. If not, set the value to 1
var ProductQty = 1;
if (formContext.getAttribute("new_courseqtytoadd").getValue() != null) {
ProductQty = formContext.getAttribute("new_courseqtytoadd").getValue();
}
var entityLogicalName = "opportunityproduct";
var data = {
"isproductoverridden": false,
"productid@odata.bind": "/products(" + ProductID_ID + ")",
"opportunityid@odata.bind": "/opportunities(" + RecordGUID + ")",
"quantity": parseInt(ProductQty),
"uomid@odata.bind": "/uoms(HARDCODED-GUID)",
"ispriceoverridden": false
}
Xrm.WebApi.createRecord(entityLogicalName, data).then(
function success(result) {
console.log("Record created with ID: " + result.id);
// perform operations on record creation
//add any other post-insert tasks to be done such as clearing fields or resetting the form etc.
},
function (error) {
console.log(error.message);
// handle error conditions
formContext.getControl("new_addskuresponse").setVisible(true);
formContext.getAttribute("new_addskuresponse").setValue(error.message);
}
);
//--Reload the subgrid values
formContext.data.refresh(true);
}
}
Interested to learn more ?
Im gonna be honest - Dynamics 365 is one of those tools that is an incredibly powerful platform for your organization. With that power, comes a certain level of complexity. If you’d like to get some real answers about how Dynamics can benefit your organization, give me a call for a quick chat to see if it’s an option for you.
Give us a call at 604.846.4402 or email info@dominicsystems.com