2
votes

I'm trying to just Javascript to add a list item when in SharePoint 2013 using the following code;

function createListItem() {

    var clientContext = new SP.ClientContext.get_current();

    var oList = clientContext.get_web().get_lists().getByTitle('CrewNoticesAudit');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);

    oListItem.set_item('Title', 'My New Item!');
    oListItem.set_item('NoticeId', 1);  // THIS IS A LOOKUP VALUE
    oListItem.set_item('User', 'administrator');
    oListItem.set_item('TimeStamp', new Date());
    oListItem.set_item('AuditType', 'Open');

    oListItem.update();

    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert('Item created: ' + oListItem.get_id());
}

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

The problem that I'm having is that NoticeId is a lookup value looking at a different list. Do I need to do something different to set a lookup value on an item?

UPDATE: sorry, cracked it. Second google more fruitful.

If anyone else is struggling, you need to create a lookup field.

    var noticeIdLookup = new SP.FieldLookupValue();
    noticeId.set_lookupId(noticeId);
2
In your example where you put the onQuerySucceeded and onQueryFailed?Douglas Santos
@DouglasSantos updated to include the example successeded and failed functionsowen79

2 Answers

5
votes

Correct way is:

var lkfieldsomthing = new SP.FieldLookupValue();

lkfieldsomthing.set_lookupId(ID_VALUE); //WHERE ID_VALUE is the unique ID 

then while setting you can use

listItem.set_item("LOOKUP_COLUMN_NAME", lkfieldsomthing )
0
votes

Or you can pass just the ID if related item instead.