Matt
Matt

Reputation: 53

Dynamics CRM 2016 - Retrieve lookupfield value

I'm using a script to populate one entity with information from another entity. It works great, i can do it for all static fields no problem at all.

However, when one of the fields is a lookup field, it doesn't work.

Could someone please point me in the right direction to get the below working?

In the below example the new_rehabconsultant field is the lookup field on the contact form. The new_UnitNumber is a static single line of text field. The new_UnitNumber is populating fine, the new_rehabconsultant lookup field isn't

function Contact_OnChange() {
var contact = Xrm.Page.getAttribute("regardingobjectid").getValue();

if (contact == null) {
    return;
}

var serverUrl = Xrm.Page.context.getClientUrl();
var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=new_UnitNumber,new_rehabconsultant&$filter=ContactId eq guid'" + contact[0].id + "'";

var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", oDataSelect, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
retrieveReq.onreadystatechange = function () {
    GetContactData(this);
};
retrieveReq.send();
}

function GetContactData(retrieveReq) {
if (retrieveReq.readyState == 4) {
    if (retrieveReq.status == 200) {
        var retrieved = JSON.parse(retrieveReq.responseText).d;
                 Xrm.Page.getAttribute("new_unitnumber").setValue(retrieved.results[0].new_UnitNumber);
    Xrm.Page.getAttribute("new_rehabconsultant").setValue(retrieved.results[0].new_rehabconsultant);
    }
}
}

Upvotes: 1

Views: 583

Answers (1)

Alex
Alex

Reputation: 23300

You're trying to fit the cube inside the triangle here, it's a problem of data model being different between oData (Entity reference) and Form (Lookup).

You should do this (slightly rewritten for readability):

function GetContactData(retrieveReq) {
    if (retrieveReq.readyState == 4) {
        if (retrieveReq.status == 200) {
            var retrieved = JSON.parse(retrieveReq.responseText).d;
            Xrm.Page.getAttribute("new_unitnumber").setValue(retrieved.results[0].new_UnitNumber);
            var record = retrieved.results[0].new_rehabconsultant;
            // mind the square brackets, lookup values are *arrays*
            var value = [{ id: record.Id, name: record.Name, entityType: record.LogicalName }];

            Xrm.Page.getAttribute("new_rehabconsultant").setValue(value);
        }
    }
}

Beware that this isn't meant to be copy-pasted but serves as a PoC about what's wrong in the OP.

Upvotes: 1

Related Questions