0

I try to create a new button in the ribbon.

When the person select a list item and click on this button this item will be copied to another list.

CommandAction=""javascript:
var context = SP.ClientContext.get_current();
var siteUrl = '/sites/calendar';
var clientContext = new SP.ClientContext(siteUrl);
var web = context.get_web();
context.load(web);

var sourceId = SP.ListOperation.Selection.getSelectedList();
var source = web.get_lists().getById(sourceId);


var oList = context.get_web().get_lists().getByTitle('Copy');
context.load(oList);

var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
alert('debut');
for(var i in selectedItems)
{
    var currentItem = source.getItemById(selectedItems[i].id);
    context.load(currentItem);
    context.executeQueryAsync(Function.createDelegate(this,test),Function.createDelegate(this,error));
}

function test(sender, args){
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', currentItem.get_item('Title'));
    oListItem.update();
    oList.update();
    alert('done');
}
function error(sender, args){ alert('error');}""

This work pretty well but only on the second time? When I select an item and click on the button I have the alert 'done', but it was not copied in the other library. But if i click again it works.

I don't understand why?

1

You need to call executeQueryAsync again after oList.update in the test function. Move your alert into the success callback of that executeQueryAsync.

It works on the second click because the executeQueryAsync in your for loop actually saves the item from the first update since that's already in the batch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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