Search This Blog

Thursday, 22 March 2012

How to Get\Set Lookup Field using ECMAScript SharePoint 2010

In this post we will explain how to get and set a lookup field using Ecmascript

Firstly, to get or retrieve a lookup field value see the below example -
function GetLookupValue()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘Testlist’);
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, ‘Include(Title,Department)’);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var TextFiled = “”;
var ListEnumerator = this.allItems.getEnumerator();
while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
TextFiled += currentItem.get_item(‘Title’) + ‘-’ +currentItem.get_item(‘Department’).get_lookupValue() + ‘\n’;
}
alert(TextFiled);
}
function failed(sender, args) {
alert(“failed. Message:” + args.get_message());
}


In the above ECMAScript Department is the Lookup and currentItem.get_item(‘Department’).get_lookupValue() will get you the value of the Lookup item selected.

Next Lets look at how to set a Lookup Field.

In this part we will look at how to set a lookup field value using ECMAScript.
function SetLookupValue()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘Testlist’);
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, ‘Include(Title,Department)’);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var TextFiled = “”;
var ListEnumerator = this.allItems.getEnumerator();
while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
var _newLookupField = new SP.FieldLookupValue();
newLookupField.set_lookupId(10) -> Updated with some lookup value for Department column
currentItem.set_item(‘Department’, newLookupField);
currentItem.update();
// Call context.executeQueryAsync again
}
}
function failed(sender, args) {
alert(“failed. Message:” + args.get_message());
}
In the above code snippet we are trying to set the value of ‘Department’ column for each item in the ‘Testlist’ . After currentItem.update(); statement you would need to call context.executeQueryAsync again to commit the changes.


No comments:

Post a Comment