// Populate Customer Address from Parent Account
function PopulateCustomerAddress(ParentAccount) {
if (ParentAccount != null) {
var AccountId = ParentAccount.getValue()[0].id;
// Pass odataQuery
var odataQuery = "AccountSet?$select=Address1_Fax,Address1_Line1,Address1_Line2,Address1_StateOrProvince,Address1_Telephone1,Address1_Telephone2,new_regionid&$filter=AccountId eq guid'" + AccountId + "'";
retrieveRecord(odataQuery, retrieveCustomerAddressCompleted, null);
}
}
// Retrieve Record Details based on the odataQuery
function retrieveRecord(odataQuery, successCallback, errorCallback) {
var context = Xrm.Page.context;
//Retrieve the server url,
serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
//odataQuery is required, i.e. "AccountSet/guid('')"
if (!odataQuery) {
alert("odataQuery is required.");
return;
}
//Asynchronous AJAX function to Retrieve a CRM record using OData
$.ajax({
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataQuery,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
//Called upon successful Retrieval of Customer Address.
function retrieveCustomerAddressCompleted(data, textStatus, XmlHttpRequest) {
//Get back the Account JSON object
var Account = data.results[0];
if (Account != null) {
Xrm.Page.getAttribute("address1_fax").setValue(Account.Address1_Fax);
Xrm.Page.getAttribute("address1_line1").setValue(Account.Address1_Line1);
Xrm.Page.getAttribute("address1_line2").setValue(Account.Address1_Line2);
Xrm.Page.getAttribute("address1_stateorprovince").setValue(Account.Address1_StateOrProvince);
Xrm.Page.getAttribute("address1_telephone1").setValue(Account.Address1_Telephone1);
Xrm.Page.getAttribute("address1_telephone2").setValue(Account.Address1_Telephone2);
// setting lookup field
if (Account.new_regionid != null && Account.new_regionid .Id != null)
SetLookupValue("new_region", Account.new_regionid .Id, Account.new_regionid .Name, Account.new_regionid .LogicalName);
}
}
// Set lookup value to a field
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}
Dont forget to add JSON and JQuery libraries to the form. you can find it in my previous posts click here