Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I created a Lookup list component using javascript and HTML to view the values of the lookup list in sharepoint 2010. and it works great for viewing.

is it possible to update the lookup field programmatically using COM (Client Object Model)?

to read the lookup, I use this code:

currList.get_item("LOOKUP_FIELD_NAME")[i].get_lookupValue();

how can i set lookup value?

share|improve this question

migrated from stackoverflow.com Sep 3 '12 at 21:28

This question came from our site for professional and enthusiast programmers.

1 Answer 1

up vote 3 down vote accepted

I found the solution:

ctx = new SP.ClientContext.get_current();

//Add code to retrieve current list item...

var newId = 11;//for exmple

var newLookupField = new SP.FieldLookupValue();
newLookupField.set_lookupId(newID);
var existingLookupValue = currList.get_item("Lookup_field_id");

if (existingLookupValue == null) {
    // set to a single lookup value because we don’t have an existing value
    currList.set_item("Lookup_field_id", newLookupField);

} else if ( existingLookupValue instanceof SP.FieldLookupValue) {
    // we need to change from a lookup field value to an array of lookup fields values
    var newLookupValue = new Array();
    newLookupValue[0] = existingLookupValue;
    newLookupValue[1] = newLookupField;
    currList.set_item("Lookup_field_id", newLookupValue);
} else if ( existingLookupValue instanceof Array) {
    // array already exists, just append
    existingLookupValue[existingLookupValue.length] = newLookupField;
    currList.set_item("Lookup_field_id", existingLookupValue);
}

currentItem.update();

ctx.executeQueryAsync(Function.createDelegate(this, this.onUpdateLookupSucceeded), Function.createDelegate(this, this.onUpdateLookupFailed));

finally, to set the lookup field empty, you can simply set its value to null

currList.set_item("Lookup_field_id", null);

HTH, Khalil.

share|improve this answer
    
Should this work in the C# version of the COM as well? –  Matt Oct 26 '12 at 1:16
    
No, This is Javascript code –  kdureidy Oct 27 '12 at 21:17
    
There's no reason it wouldn't work in C#. It's the same COM but the API is, understandably, different. –  Stécy Mar 1 '13 at 19:12
    
I am not saying it's undoable using C# COM APIs, it's just different approach. if you want to use C#, there is no need to use the code above –  kdureidy Mar 2 '13 at 19:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.