I have a custom entity form in CRM. When the user selects an opportunity, I want to populate the form data with values from the selected opportunity.

I quickly realize that I cannot use the CRM Business Rules functionality for this, because it does not currently support setting field values from related entity data. So I decide to use a client-side OData query to handle this functionality and am learning a lot about how to handle certain OData field types.

My OData query looks like this:
function PopulateOpportunityData(oppId) {
var ODataHost = location.protocol + ‘//’ + location.host + ‘/’ + Xrm.Page.context.getOrgUniqueName();
var ODataService = “/XRMServices/2011/OrganizationData.svc”;
var ODataQuery = “/OpportunitySet?$select=EstimatedCloseDate,CustomerId,Cat_RevenueMonths,Description&$filter=OpportunityId eq guid’” + oppId.toString() + “’”;
var ODataURL = ODataHost + ODataService + ODataQuery;
$.ajax({
type: “GET”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
var opp = data.d.results;
if (opp == null || opp.length == 0) {
return;
}
var endDate = null;
var projectMonths = HandleODataInt(opp[0].Cat_RevenueMonths);
projectMonths = projectMonths == null ? 1 : projectMonths;
var startDate = HandleODataDate(opp[0].EstimatedCloseDate);
if (startDate != null) {
Xrm.Page.getAttribute(“cat_startdate”).setValue(startDate);
endDate = startDate.addMonths(projectMonths);
Xrm.Page.getAttribute(“cat_enddate”).setValue(endDate);
}
var account = opp[0].CustomerId;
if (account != null) {
Xrm.Page.getAttribute(“cat_account”).setValue([{ id: account.Id, name: account.Name, entityType: account.LogicalName }]);
}
},
error: function (XmlHttpRequest, textStatus, errorObject) {
     var errorCode = 1;
}
});
}

The first thing I notice about the date field is that it comes back looking something like this: “/Date(1385704800000)/”, which is not entirely intuitive.

With dates, you have to strip away the extra stuff, convert the number to an integer value, and then pass it into a new date function, like this:

function HandleODataDate(dateValue) {

var returnValue = null;

try

{

dateValue = dateValue == null ? “” : dateValue.toString();

if (dateValue != “”) {

dateValue = dateValue.replace(“/”, “”);

dateValue = dateValue.replace(“Date(“, “”);

dateValue = dateValue.replace(“)”, “”);

dateValue = dateValue.replace(“/”, “”);

var returnValue = new Date(parseInt(dateValue));

returnValue = isNaN(returnValue) ? null : returnValue;

}

}

catch (Exception) { }

return returnValue;

}

And then “/Date(1385704800000)/” becomes this:

Advertisements