CRM 2013 Setting Field Value from OData Lookup Field Result

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.

One of the fields I want to populate is the Account field with the Account entity that is related to the selected Opportunity.

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;

}

});

}

When an Opportunity is selected, I get an Account object back:

var account = opp[0].CustomerId;

I want to set my field entitled "cat_account" to this lookup value. This is how you do it in CRM 2011 or CRM 2013:

Xrm.Page.getAttribute("cat_account").setValue([{ id: account.Id, name: account.Name, entityType: account.LogicalName }]);

 

One Response

  1. Lucas July 10, 2014

Leave a Reply