Retrieve, Create, Update, Delete data Client side using XRM Web API and FetchXML in Dynamics 365
The XRM WebAPI is a great way to achieve CRUD operation from client side scripts. Below are the code snippets to explain how we use it.
Retrieve Single Record
Xrm.WebApi.retrieveRecord("account", "a8a19cdd-88df-e311-b8e5-6c3be5a8b200", "?$select=name,revenue").then( function success(result) { console.log("Retrieved values: Name: " + result.name + ", Revenue: " + result.revenue); // perform operations on record retrieval }, function (error) { console.log(error.message); // handle error conditions } );
Retrieve Multiple Record
Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name,_primarycontactid_value&$filter=primarycontactid/contactid eq a0dbf27c-8efb-e511-80d2-00155db07c77").then( function success(result) { for (var i = 0; i < result.entities.length; i++) { console.log(result.entities[i]); } // perform additional operations on retrieved records }, function (error) { console.log(error.message); // handle error conditions } );
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 } );
Thanks for reading.