Usually when we select a value in a lookup field it displays the Primary Name Field in the text after selection. However it holds the PrimaryIDField in the background.
While working in a requirement a need arrises to display a field in the LookUp display which is not a PrimaryNameField.
Let’s concider the Account Lookup here.
Requirement
Display Account number in the display field instead of the AccountName (Which is a PrimaryNameField) in every Account Lookup.
JavaScript
function ChangeLookUpDisplayValue(fieldname){ var lookupData = new Array(); var lookupItem= new Object(); var lookup = document.getElementById(fieldname); if (lookup != null && lookup.DataValue != null){ lookupItem.id = lookup.DataValue[0].id; lookupItem.typename = lookup.DataValue[0].typename; var displayvalue=''; var xmlText=''; xmlText +=""; xmlText +=""; xmlText +=""; xmlText += "account"; xmlText += ""+ lookup.DataValue[0].id +""; xmlText += ""; xmlText += "false"; xmlText += ""; xmlText += "accountnumber"; xmlText += ""; xmlText += ""; xmlText += ""; xmlText += ""; xmlText +=""; var xHReq = new XMLHttpRequest(); var url=Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web"; xHReq.open("POST", url, false); xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Retrieve"); xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); xHReq.setRequestHeader("Accept", "application/xml, text/xml, */*"); xHReq.send(xmlText); // Capture the result. var resultXml = xHReq.responseXML; var varray = new Array(); // Check for errors. var errorCount = resultXml.selectNodes('//s:Fault').length; if (errorCount != 0) { var msg = resultXml.selectSingleNode('//faultstring').nodeTypedValue; alert(msg); } else { var result = resultXml.getElementsByTagName("a:KeyValuePairOfstringanyType"); if(result.length>0) { displayvalue= result[0].childNodes[1].lastChild.text; } if(displayvalue!='') { lookupItem.name = displayvalue; lookupData[0] = lookupItem; lookup.DataValue = lookupData; } } } }
Description
Extract the AccountId from the Lookup. Query this from the account antity using the SOAP message. Extract the AccountNumber filed value. Finally create a new look up object with having the AccountNumber field value in the display name and assign this to the lookup.
Usage
Create a Webresource and put this method to the WebResource. Use the same web resource in the form where you want to implement this functionality and use the above function (ChangeLookUpDisplayValue) in the lookup field change. Pass the Lookup field name as parameter to the function.