In our last article, we discussed Xrm.WebApi Create, Update, and Delete method. In this article, we are going to provide sample code for using Xrm.WebApi Retrieve method.
Many times, we required to set up field mapping between the parent and child entities, for example - let’s say we need to bring the following information based on the account selected under Contact entity. We can easily set these fields' mapping by editing the Account and Contact relationship. But, that relationship mapping will only work when the contact record is created from the Account entity form.
However, if we are creating the contact record directly, the relationship mapping won’t work here. So, in this article, we are providing a sample code to implement the above mapping using Retrieve method.
-
- function retrieveAccountDetails() {
-
- if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null && Xrm.Page.getAttribute("parentcustomerid").getValue()[0].id != null) {
- var accountid = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].id;
-
-
- Xrm.WebApi.retrieveRecord("account", accountid, "?$select=telephone1,new_verificationrequired,new_activationdate,address1_shippingmethodcode&$expand=parentaccountid($select=accountid,name)").then(
- function success(result) {
- if (result != null) {
-
- if (result.telephone1 != null)
- Xrm.Page.getAttribute("telephone1").setValue(result.telephone1);
-
- if (result.parentaccountid != null) {
- var object = new Array();
- object[0] = new Object();
- object[0].id = result.parentaccountid.accountid;
- object[0].name = result.parentaccountid.name;
- object[0].entityType = "account";
- Xrm.Page.getAttribute(new_parentaccount).setValue(object);
- }
-
- if (result.new_verificationrequired != null)
- Xrm.Page.getAttribute("new_verificationrequired").setValue(result.new_verificationrequired);
-
- if (result.new_activationdate != null)
- Xrm.Page.getAttribute("new_activationdate").setValue(new Date(result["[email protected]"]));
-
- if (result.address1_shippingmethodcode != null)
- Xrm.Page.getAttribute("address1_shippingmethodcode").setValue(result.address1_shippingmethodcode);
- }
- },
- function(error) {
- alert(error.message);
-
- }
- );
- }
- }
The above code is self-explanatory. It can be modified based on the required fields that we want to fetch from the parent entity and can call the above function on onChange of the lookup field for parent entity. For example, in the above scenario, it can be used on onChange of the "parentcustomerid" lookup field.
Stay tuned for more Dynamics 365 Sample code !!