Getting all values from a lookup field in SharePoint using ECMAScript client object model

I recently had a requirement wherein I had to retrieve all the values of a lookup column of a list and bind it to a dropdown using ECMAScript client object model. The tricky part is that the lookup list and column name are not known and thus are to be retrieved dynamically.

I see that there are articles describing to do the same with a choice field but none for a lookup field. So I tried to figure out a way to it for a lookup field.

First in order to accomplish this we need to find the name or GUID of the list and the column which is being used as a lookup column. The below code is used in order to do that:

var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle(listName);
var field = list.get_fields().getByInternalNameOrTitle(fieldName);

//Cast the above column as a lookup column
var lookUpField = context.castTo(field, SP.FieldLookup);

//Load the above castes lookup field
context.load(field);

//Call executeQueryAsync and pass in success and failure anonymous functions
context.executeQueryAsync(function () {

   //lookUpField.get_lookupList() gives the GUID of the lookedup list
   var lookUpListId = lookUpField.get_lookupList();

   //lookUpField.get_lookupField() gives the title of the lookedup field
   var lookUpFieldName = lookUpField.get_lookupField();

   //The onFieldLoaded function is called where we process the lookedup list and field to retrieve the values
   onFieldLoaded(lookUpListId, lookUpFieldName);
},
function (sender, args) {
   console.log(args);
});

Now that you have got the GUID of the lookedup list and the name of the lookedup field, we go ahead and write the code for retrieving all the values of the lookedup field in the OnFieldLoaded() function.

function onFieldLoaded(listID, FieldName) {
  var list = context.get_web().get_lists().getById(listID);
  var query = new SP.CamlQuery();
  query.set_viewXml('<View/>');

  var listItems = list.getItems(query);
  context.load(listItems,'Include('+FieldName+')');
  context.executeQueryAsync(
  function () {
    for (i = 0; i < listItems.get_count() ; i++){
    console.log(listItems.itemAt(i).get_item(FieldName));
    }
  },
  function (request, error) {
    console.log(error);
  });
}
Advertisements