Thursday, April 4, 2013

SharePoint 2010 retrieving lookup values using ECMAScript

Script to retrieve single and multiple value lookup fields values using SharePoint 2010 Client Object Model for JavaScript (ECMAScript):


var listName = "list name here";
var listItemId = 23; // id here

function retrieveLookupValues() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(listName);
    var selectedItems = SP.ListOperation.Selection.getSelectedItems();
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("< View >< Query >< Where >< Eq >< FieldRef Name='ID' / >< Value Type='Counter'>" + listItemId + "< /Value>< /Eq>< /Where>< /Query>< RowLimit>100< /RowLimit>< /View>");
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem, 'Include(CustomSingelLookupFld, CustomMultilLookupFld)');
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
 var listInfo = "";
    var listItemEnumerator = collListItem.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        // get single value LookupField:
        var oCustomSingelLookupFld = oListItem.get_item("CustomSingelLookupFld");
  listInfo += "oCustomSingelLookupFld.Value = " + oCustomSingelLookupFld.get_lookupValue() + " \t oCustomSingelLookupFld.Id = " + oCustomSingelLookupFld.get_lookupId();
  // get multiple value LookupField:
        var oCustomMultilLookupFld = oListItem.get_item("CustomMultilLookupFld");
  for(var ix = 0; ix < oCustomMultilLookupFld.length; ix++){
   listInfo += "oCustomSingelLookupFld[" + ix + "].Value = " + oCustomMultilLookupFld[ix].get_lookupValue() + " \t oCustomSingelLookupFld[" + ix + "].Id = " + oCustomMultilLookupFld[ix].get_lookupId();
  }
    }
 alert(listInfo);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message());
}

Post a Comment