Monday 8 May 2017

Update lookup field or person field in jsom

When we talk about how to update lookup field or person or group field using jsom then it is treated little diffirently.
for example, for normal field we use

listitemobj.set_item(fieldname,value)
but that will not work for lookup fields.
for lookup fields following step should be followed.

to update person or group field we should pass id of the person or group.

for example if id of the user is 5 then update should be like below.

listitemobj.set_item(personfieldname,5);

similarly for lookup field, a lookup field value should be created first.

example:
var lookupfieldvalue = new SP.FieldLookupValue();
 lookupfieldvalue.set_lookupId(<id of the item to lookup>);
 oListItem.set_item(lookupfield, lookupfieldvalue);
 oListItem.update();

if we summarise both in a function then

function createListItem(personfield,lookupfield) {

        var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle(<list name>);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);

// set person field
        oListItem.set_item(personfield, <id of the user or group>);

//set lookupfield
var lookupfieldvalue = new SP.FieldLookupValue();
        lookupfieldvalue.set_lookupId(<id of the item to lookup>);
        oListItem.set_item(lookupfield, lookupfieldvalue);
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),      Function.createDelegate(this, this.onQueryFailed));
    }

    function onQuerySucceeded() {
        alert('Item created Successfully !!!!');
    }

    function onQueryFailed(sender, args) {

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
  

No comments:

Post a Comment

Setup dev environment for spfx

So lets setup dev environment for SharePoint Framework abbreviated as SPFX. for an Introduction of What is SPFX and What are the capebiliti...