Wednesday, September 12, 2012

Data Access using O-Data Service in CRM 2011.

Introduction

Here I am going to show you how to access the Data using O-Data service.
Here the Scenario..Lets see In Contact Form when I Select the Parent Customer the Main Phone of the Parent Customer value will be stored in Home Phone of the Contact.For that we have ro create a Function and call the Function in Onchange Event of that ParentCustomer in Contact Form.

function checkParentAccountPhone()
{
       //alert("hello");
if(Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue() != null)
{
                   // if  CRM has multiple organization.                    
                   var serverUrl = location.protocol + '//' + location.host+ '/' +  Xrm.Page.context.getOrgUniqueName();;
                  //else
                   var serverUrl = location.protocol + '//' + location.host;
                   var parentid=Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].id;
   alert(parentid);
   var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";

  oDataEndpointUrl += "AccountSet?$select=Telephone1&$filter=AccountId eq guid'" +  parentid + "'"
  var service = GetRequestObject();
                  Xrm.Page.getAttribute("address1_line1").setValue(oDataEndpointUrl );
  if (service != null)
 {
service.open("GET", oDataEndpointUrl, false);
       service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
service.send(null);
var requestResults = eval('(' + service.responseText + ')').d;

if (requestResults != null && requestResults.results.length > 0)
{
                                 Xrm.Page.getAttribute("telephone2").setValue(requestResults.results[0].Telephone1);

}
}
    }
    return false;
}
function GetRequestObject()
{
    if (window.XMLHttpRequest)
        return new window.XMLHttpRequest;
    else
    {
        try
        {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex)
        {
            return null;
        }
    }
}

function errorDisplay(XmlHttpRequest, textStatus, errorThrown)
{
     alert(errorThrown);
}

Save above in .js File.and Call the Function checkParentAccountPhone from OnChange Event of Parent Customer.
For How to call Javascript use my below link

http://microsoftcrmkartik.blogspot.in/2012/06/javascript-in-crm-2011.html

No comments:

Post a Comment