Hello,
Let's quickly learn on CRUD, Associate, Disassociate, Assign, Share using Xrm.WebApi.
- Create 3 entities-
- College Stream:
- Display Name: College Stream
- Plural Name: College Streams
- Schema Name: new_collegestream
- Fields:
- Name (Single line of text)
- College Student-
- Display Name: College Student
- Plural Name: College Students
- Schema Name: new_collegestudent
- Fields:
- Name (Single line of text)
- College Stream (new_CollegeStreamId) (LookUp to College Stream)
- College Subject:
- Display Name: College Subject
- Plural Name: College Subjects
- Schema Name: new_collegesubject
- Fields:
- Name (Single line of text)
- College Stream (new_CollegeStreamId) (LookUp to College Stream)
- Create Relationships:
- College Stream:
- 1:N Relationship:
- Related Entity - College Student
- Relationship Name: new_new_collegestream_new_collegestudent
- 1:N Relationship:
- Related Entity - College Subject
- Relationship Name: new_new_collegestream_new_collegesubject
- College Student:
- N:N Relationship:
- Other Entity - College Subject
- Relationship Definition:
- Name: new_new_collegestudent_new_collegesubject
- Relationship Entity Name: new_new_collegestudent_new_collegesubject
- Add Lookup fields (College Stream) on "College Student" and "College Subject" entity form.
- Add subgrid (new_subgrid_collegesubject) of "College Subject" entity on "College Student" entity form.
- Create a JavaScript file named "CollegeStudent.js". Once upload, it's schema name will be "new_collegestudent.js".
- Add below structure:
var CollegeStudent; (function (CollegeStudent) { class Student { //Write All Your Code Here } CollegeStudent.Student = Student; })(CollegeStudent || (CollegeStudent = {}));
- CREATE:
static createRecord(formContext) { const data = JSON.parse('{' + '"new_name":"Mahesh"' + '}'); Xrm.WebApi.createRecord("new_collegestudent", data).then( function success(result) { var alertStrings = { confirmButtonLabel: "OK", text: "Record created with ID: " + result.id, title: "Message Box" }; 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); } ); }, function (error) { console.log(error.message); } ); }
- UPDATE:
static updateRecord(formContext) { const recordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); const data = JSON.parse('{' + '"new_name":"Mahesh Updated"' + '}'); Xrm.WebApi.updateRecord("new_collegestudent", recordId, data).then( function success(result) { var alertStrings = { confirmButtonLabel: "OK", text: "Record updated with ID: " + result.id, title: "Message Box" }; 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); } ); }, function (error) { console.log(error.message); } ); }
- DELETE:
static deleteRecord(formContext) { const recordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); Xrm.WebApi.deleteRecord("new_collegestudent", recordId).then( function success(result) { var alertStrings = { confirmButtonLabel: "OK", text: "Record deleted with ID: " + result.id, title: "Message Box" }; 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); } ); }, function (error) { console.log(error.message); } ); }
- RETRIEVE:
- The IF condition is written to just extract the recordId from Form. In general, the recordId is sent through function parameter.
static retrieveRecord(formContext, recordId) { if (recordId == null || recordId == "") { recordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); } const recordResponse = Xrm.WebApi.retrieveRecord('new_collegestudent', recordId).then( function success(result) { var alertStrings = { confirmButtonLabel: "OK", text: "Record retrieved with ID: " + result.new_collegestudentid, title: "Message Box" }; 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); } ); }, function (error) { console.log(error.message); } ); }
RETRIEVE MULTIPLE:
- There are multiple ways to execute retrieveMultiple. We can pass fetchXML as an input parameter as well. We can pass array of recordIds to be fetched and can create fetchXML inside the function as well.
static retrieveMultipleRecords(formContext) { Xrm.WebApi.online.retrieveMultipleRecords('new_collegestudent').then( function (success) { if (success.entities.length > 0) { var selectedRecords = []; success.entities.forEach(function (singleRecord) { selectedRecords.push({ singleRecord }) }); console.log(selectedRecords); } else { } var alertStrings = { confirmButtonLabel: "OK", text: " Multiple records (Total: " + success.entities.length + ") retrieved successfully.", title: "Message" }; var alertOptions = { height: 120, width: 260 }; Xrm.Navigation.openAlertDialog(alertStrings, alertOptions); }, function (error) { console.log(error); } ); }
- ASSOCIATE:
- Associate is a combination of retrieveMultiple and Associate. If you don't have the collection of records that need to be associated then you have to first execute the retrieveMultiple with filterXML and then execute Associate. If you have the collection of records that need to be associated then you can directly execute Associate.
static associateRecords(formContext) { var relatedRecords = []; var selectedRecords = []; try { const parentEntityLogicalName = formContext.data.entity.getEntityName(); const parentRecordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); const selectedStream = formContext.getAttribute("new_collegestreamid").getValue(); const filterXML = '<fetch version="1.0" output-format="xml - platform" mapping="logical" distinct="false">' + '<entity name="new_collegesubject">' + ' <attribute name="new_collegesubjectid" />' + ' <filter>' + ' <condition attribute="new_collegestreamid" operator="eq" value="' + selectedStream[0].id.replace("{", "").replace("}", "") + '" />' + ' </filter>' + '</entity>' + '</fetch >'; var filterOptions = (filterXML.length > 0) ? (`?fetchXml=${filterXML}`) : ""; Xrm.WebApi.online.retrieveMultipleRecords('new_collegesubject', filterOptions).then( function (success) { if (success.entities.length > 0) { success.entities.forEach(function (singleRecord) { selectedRecords.push({ singleRecord }) }); if (selectedRecords.length > 0) { selectedRecords.forEach(function (singleRecord) { relatedRecords.push({ "entityType": "new_collegesubject", "id": singleRecord.singleRecord.new_collegesubjectid }); }); const manyToManyAssociateRequest = { getMetadata: () => ({ boundParameter: null, parameterTypes: {}, operationType: 2, operationName: "Associate" }), relationship: "new_new_collegestudent_new_collegesubject", target: { "entityType": parentEntityLogicalName, "id": parentRecordId }, relatedEntities: relatedRecords }; Xrm.WebApi.online.execute(manyToManyAssociateRequest).then( (success) => { var alertStrings = { confirmButtonLabel: "OK", text: "Records associated successfully.", title: "Message" }; var alertOptions = { height: 120, width: 260 }; Xrm.Navigation.openAlertDialog(alertStrings, alertOptions); formContext.getControl("new_subgrid_collegesubject").refresh(); }, (error) => { Xrm.Navigation.openErrorDialog({ message: error.message }); } ); } } }, function (error) { console.log(error); } ); } catch (error) { Xrm.Navigation.openErrorDialog({ message: error }); } }
- DISASSOCIATE:
static disassociateRecords(formContext, selectedRecords) { var relatedRecords = []; const parentEntityLogicalName = formContext.data.entity.getEntityName(); const parentRecordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); try { //if (selectedRecords.entities.length > 0) { if (selectedRecords.length > 0) { selectedRecords.forEach(function (singleRecord) { const manyToManyDisassociateRequest = { getMetadata: () => ({ boundParameter: null, parameterTypes: {}, operationType: 2, operationName: "Disassociate" }), relationship: "new_new_collegestudent_new_collegesubject", target: { "entityType": parentEntityLogicalName, "id": parentRecordId }, relatedEntityId: singleRecord //singleRecord[childEntityLogicalName + "id"] }; relatedRecords.push(manyToManyDisassociateRequest); }); Xrm.WebApi.online.executeMultiple(relatedRecords).then( (success) => { var alertStrings = { confirmButtonLabel: "OK", text: "Records disassociated successfully.", title: "Message" }; var alertOptions = { height: 120, width: 260 }; Xrm.Navigation.openAlertDialog(alertStrings, alertOptions); formContext.getControl("new_subgrid_collegesubject").refresh(); }, (error) => { Xrm.Navigation.openErrorDialog({ message: error.message }); } ); } } catch (error) { Xrm.Navigation.openErrorDialog({ message: error }); } }
- SHARE:
static shareRecord(formContext) { try { const recordId = formContext.data.entity.getId().replace("{", "").replace("}", ""); const entityName = formContext.data.entity.getEntityName(); const fieldName = entityName + "id"; var target = { "new_collegestudentid": recordId, //put <other record type>id and Guid of record to share here "@odata.type": "Microsoft.Dynamics.CRM." + entityName //replace account with other record type }; var principalAccess = { "Principal": { "systemuserid": "7a172881-fdb3-4571-a7e5-b1f5bbb7850d", //put teamid here and Guid of team if you want to share with team "@odata.type": "Microsoft.Dynamics.CRM.systemuser" //put team instead of systemuser if you want to share with team }, "AccessMask": "WriteAccess" //full list of privileges is "ReadAccess, WriteAccess, AppendAccess, AppendToAccess, CreateAccess, DeleteAccess, ShareAccess, AssignAccess" }; var parameters = { "Target": target, "PrincipalAccess": principalAccess }; const clientURL = Xrm.Utility.getGlobalContext().getClientUrl(); var req = new XMLHttpRequest(); req.open("POST", clientURL + "/api/data/v9.0/GrantAccess", true); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.onreadystatechange = function () { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 204) { //Success - No Return Data - Do Something } else { var errorText = this.responseText; //Error and errorText variable contains an error - do something with it } } }; req.send(JSON.stringify(parameters)); } catch (error) { console.log(error); } }
- ASSIGN:
- The correct version of API will be obtained from Settings >> Customizations >> Developer Resources >> Instance Web API
static assignRecord(formContext) { try { const entityName = formContext.data.entity.getEntityName(); const entityId = formContext.data.entity.getId().replace("{", "").replace("}", ""); const assigneeId = "7a172881-fdb3-4571-a7e5-b1f5bbb7850d"; var entity = {}; entity["ownerid@odata.bind"] = "/systemusers(" + assigneeId + ")"; //var impersonateUserId = "A734DA29-7993-DE11-BECE-005056B47DB0";// GUID of the system administrator var req = new XMLHttpRequest(); req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v9.2/" + entityName + "s" + "(" + entityId + ")", false);// my entity name is new_workitem req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); //req.setRequestHeader("MSCRMCallerID", impersonateUserId); req.onreadystatechange = function () { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 204) { //Success - No Return Data - Do Something } else { Xrm.Utility.alertDialog(this.error); } } }; req.send(JSON.stringify(entity)); } catch (error) { console.log(error); } }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.