Archive
JScript to Create record and its related record using Web API – CRM 2016
Below is the script snippet to create ‘Account’ record using Web API.
function createAccount() {
var clientUrl = Xrm.Page.context.getClientUrl();var req = new XMLHttpRequest()
req.open(“POST”, encodeURI(clientUrl + “/api/data/v8.0/accounts”), true);
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.setRequestHeader(“Prefer”, “odata.include-annotations=*”);// Set Account Object
var objAccount = {};
objAccount.name = “Rajeev Associates”;
objAccount.creditonhold = false;
objAccount.accountcategorycode = 1;
objAccount.revenue = 123456;// Create new Contact and Set as ‘Primary Contact’
objAccount.primarycontactid = {};
objAccount.primarycontactid.firstname = “Hello”;
objAccount.primarycontactid.lastname = “Lobo”;// Set existing Contact as ‘Primary Contact’
//objAccount[‘primarycontactid@odata.bind’] = “/contacts(” + { contact GUID } + “)”;//convert JSON object to string
var body = JSON.stringify(objAccount);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 204) {
var accountUri = this.getResponseHeader(“OData-EntityId”);// Get Account GUID
var accountID = accountUri.split(/[()]/);
accountID = accountID[1];Xrm.Utility.alertDialog(“Created Account ID : ” + accountID);
}
}
};req.send(body);
}
- To set the lookup you need to fetch the Contact GUID first and set to ‘primarycontactid@odata.bind’. ‘@odata.bind’ is suffix and ‘primarycontactid‘ is the schema name of lookup.
- Below is sample script to retrieve Contact GUID by Fullname
function getPrimaryContact() {
var clientUrl = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest();
req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/contacts?$select=fullname&$filter=fullname eq ‘John Miller'”), true);
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 == 200) {
var data = JSON.parse(this.response);
var dat = data.value;// Loop through ‘Contact’ result set
for (var i = 0; i < dat.length; i++) {// Get ‘Contact ID’ from Contact record.
var contactId = dat[i].contactid;
if (contactId) {Xrm.Utility.alertDialog(“Contact ID : ” + contactId);
}
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error retrieving contact – ” + error.message);
}
}
};req.send();
}
🙂
CRM 2016 Web API – Retrieve a record
Below is the sample script to retrieve an Account record using Web API.
Key Points to perform Retrieve:
- Use ‘GET’ request while performing Retrieve
- ‘Status’ code would be 200.
Sample Script:
function retrieveAccounts() {
var clientURL = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest()
req.open(“GET”, encodeURI(clientURL + “/api/data/v8.0/accounts?$select=name&$top=1”), true);
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 == 200) {
var data = JSON.parse(this.response, dateReviver);
if (data && data.value) {
for (var indxAccounts = 0; indxAccounts < data.value.length; indxAccounts++) {
var accountName = data.value[indxAccounts].name;
var eTag = data.value[indxAccounts][‘@odata.etag’];
}
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error retrieving Accounts – ” + error.message);
}
}
};req.send(null);
}function dateReviver(key, value) {
var a;
if (typeof value === ‘string’) {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] – 1, +a[3], +a[4], +a[5], +a[6]));
}
}
return value;
};
ETag:
- Each time when we retrieve a record, it will include a @odata.etag field.
- We don’t need to include it in a $select system query option.
- The value of this property is updated each time the entity is updated.
- This will be used while performing optimistic concurrency to detect whether an entity has been modified since it was last retrieved.
🙂
Retrieve associated records (N:N related)
In CRM, If you create N:N relationship between 2 entities, it creates an intermediate entity (i.e., Relationship Entity) with 3 fields
- Primary key field of “Relationship Entity”
- Entity 1 Primary Key field
- Entity 2 Primary Key field
In this sample, I have 2 custom entities “Bike” and “Bond” with N:N association. (i.e., A ‘Bike’ can have N no of ‘Bonds’ and a ‘Bond’ can be associate with N ‘Bikes’)
To get all the ‘Bonds’ of ‘Bike’ with name “Honda”, below is the query expression.
string entity1 = “raj_bike”;
string entity2 = “raj_bond”;
string relationshipEntityName = “raj_bike_bond”;
QueryExpression query = new QueryExpression(entity1);
query.ColumnSet = new ColumnSet(true);
LinkEntity linkEntity1 = new LinkEntity(entity1, relationshipEntityName, “raj_bikeid”, “{Entity 1 Primary key field (i.e.,raj_bikeid)}“, JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity(relationshipEntityName, entity2, “raj_bondid”, “{Entity 2 Primary key field (i.e.,raj_bondid)}“, JoinOperator.Inner);
linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);
// Add condition to match the Bike name with “Honda”
linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“raj_bikename”, ConditionOperator.Equal, “Honda”));
EntityCollection collRecords = service.RetrieveMultiple(query);
Note : To retrieve columns from Entity 2, set ‘Alias’ to ‘LinkEntity2’.
🙂
Retrieve multiple records synchronously using OData & JQuery in CRM 2011
Hi,
Below is the Jscript function to retrieve multiple records synchronously using OData & JQuery.
function retrieveMultipleSync(odataSetName, select, filter) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;
if (select) {
odataUri += “$select=” + select ;
}
if (filter) {
odataUri += “&” + “$filter=” + filter;
}
var service = GetRequestObject();
if (service != null) {
service.open(“GET”, odataUri, false);
service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);
service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);
service.send(null);
var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;
return requestResults;
}
}
function GetRequestObject() {
var req = false;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
return req;
}
- Copy & Paste above method to a new .jscript file
- Replace double quotes(“) symbols with your keyboard double quotes
- Add the new .jscript file as web resource to CRM application
- Add “Jquery” & json” helper classes as web resources
How do I call this method :-
- In my sample below, I will show you how to read “Contacts” of an “Account”
function retrieveContactsByAccountId(accountId) {
// Pass ‘Contact’ set name since we are reading Contacts
var oDataSetName = “ContactSet”;
// Column names of ‘Contact’ (Pass * to read all columns)
var columns = “FirstName,LastName”;
// Prepare filter
var filter = “AccountId/Id eq guid'” + accountId + “‘”;
var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
if (requestResults != null) {
if (requestResults.results != null && requestResults.results.length > 0) {
for (var indxContacts = 0; indxContacts < requestResults.results.length; indxContacts++) {
var contact = requestResults.results[indxContacts];
if (contact.FirstName) {
alert(“Contact’s First Name – ” + contact.FirstName);
}
}
}
}
else {
alert(“Error while retrieving; Error – ” + service.responseText);
}
}
Get OData URI conventions from here
🙂
Retrieve record using OData and JQuery in CRM 2011
Hi,
Below is the script to read a record using OData & JQuery
function retrieveRecord(id, odataSetName) {
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
//Asynchronous AJAX function to Retrieve a CRM record using OData
$.ajax({
type: “GET”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
readRecord(data, textStatus, XmlHttpRequest)
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert(“Error – ” + errorThrown)
}
});
}
function readRecord(data, textStatus, XmlHttpRequest) {
alert(“Record read successfully!!”);
var account = data;
alert(“Name – ” + account.d.Name);
alert(“Id – ” + account.d.AccountId);
}
How do I call this method :-
- Below is the sample function to read Account
var accountId = “”; // Assign account GUID
var odataSetName = “AccountSet”;
retrieveRecord(accountId,odataSetName );
Hope it helps 🙂