Friday 19 October 2012

How to use JavaScript to Query the CRM oData Service

My previous post explained the oData features and how you could build an oData query to retrieve data via the CRM 2011 REST service, and as promised here is a nice example of how you can put this into practice. 

Background Requirements
When creating or updating the Parent Customer field on a Contact record, we want to retrieve the Address of the Parent Customer record and populate the address fields on the Contact record.

Note: The parent customer can be either an Account or Contact

Solution
1. First we need to create two JScript web references. To do this you need to go to Settings > Customizations > Customize the System || Solution
    1. JQuery - very useful in general, primarily we want to use the Ajax features
    2. Contact Parent Customer - this is where our custom JavaScript will live

2. Now we need to add these to the CRM Contact Form. To do this, you need to click on the customize form option for the Contact entity and then click on the Change Properties button in the ribbon. The below window will be displayed where you need to add both web references to the form libraries section:

3. Now we want to write our JScript code and store this in our Contact Parent Customer web reference. Go and edit the Contact Parent Customer web reference and paste the code below:

Code

function GetParentAddress()
{
//CRM REST Endpoint
var oDataEndpoint = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc";
//Clear existing field values
Xrm.Page.getAttribute("address1_name").setValue("");
Xrm.Page.getAttribute("address1_postalcode").setValue("");
Xrm.Page.getAttribute("address1_line1").setValue("");
Xrm.Page.getAttribute("address1_line2").setValue("");
Xrm.Page.getAttribute("address1_line3").setValue("");
Xrm.Page.getAttribute("address1_city").setValue("");
Xrm.Page.getAttribute("address1_stateorprovince").setValue("");
Xrm.Page.getAttribute("address1_addresstypecode").setValue("");
Xrm.Page.getAttribute("address1_country").setValue("");
//Get Parent Customer Id & Parent Customer Type
var id = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].id;
var parentType = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].typename; 
//Build Query
var oDataQuery = oDataEndpoint + ((parentType=="account") ? "/AccountSet?$filter=AccountId " : "/ContactSet?$filter=ContactId ");
oDataQuery += "eq guid'" + id + "'";

$.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: oDataQuery,
  beforeSend: function (XMLHttpRequest) 
  { 
XMLHttpRequest.setRequestHeader("Accept", "application/json"); 
  },
  success: function (data, textStatus, XmlHttpRequest)
  {
//success - populate fields on Contact Screen
Xrm.Page.getAttribute("address1_name").setValue(data.d.results[0].Address1_Name);
Xrm.Page.getAttribute("address1_postalcode").setValue(data.d.results[0].Address1_PostalCode);
Xrm.Page.getAttribute("address1_line1").setValue(data.d.results[0].Address1_Line1);
Xrm.Page.getAttribute("address1_line2").setValue(data.d.results[0].Address1_Line2);
Xrm.Page.getAttribute("address1_line3").setValue(data.d.results[0].Address1_Line3);
Xrm.Page.getAttribute("address1_city").setValue(data.d.results[0].Address1_City);
Xrm.Page.getAttribute("address1_stateorprovince").setValue(data.d.results[0].Address1_StateOrProvince);
if (data.d.results[0].Address1_AddressTypeCode != null)
{
Xrm.Page.getAttribute("address1_addresstypecode").setValue(data.d.results[0].Address1_AddressTypeCode.Value);
}
Xrm.Page.getAttribute("address1_country").setValue(data.d.results[0].Address1_Country);
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) 
  { 
//failed
alert('oData Query Error: ' + oDataQuery); 
  }
});
}

4. Now we need to set the Parent Customer field OnChange event on the Contact form to trigger the GetParentAddress() function every time the value changes. To do this, navigate back to the Customize Contact Form window:

5. Click on the Parent Customer field and then click on the Change Properties button in the ribbon.

6. On the Events tab select the Parent Customer field from the Control drop-down and Add a new OnChange event.

7. Select the Contact Parent Customer library from the drop-down, and set the function to GetParentAddress as displayed below. 

8. Save and then Publish All Changes. 

Testing our Solution
I have created a new Account and a new Contact record, both with different addresses. 

Now when we change the Parent Customer field on any Contact record, either when we create or update a record we should notice the Contact address fields should auto-populate to the address values of the parent customer as shown below:

Test 1 Parent Customer = Account

Test 2 Parent Customer = Contact



No comments:

Post a Comment

Action Microsoft.Crm.Setup.Common.Analyzer +CollectAction failed. Fatal error during installation

When installing the Srs Data Connection (Microsoft Dynamics CRM Reporting Extensions), you may have experienced the following error: ...