1

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?

1 Answer 1

3

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.

4
  • Should this work in the C# version of the COM as well?
    – Matt
    Oct 26, 2012 at 1:16
  • No, This is Javascript code
    – kdureidy
    Oct 27, 2012 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, 2013 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, 2013 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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