I am trying to develop My Favourite functionality in Sharepoint using the below approach.
- Create My Favourite list
- Create a custom script that will read the selection of the list item (any other list in the site)
- Based on number of items selected, get the id of each item and save the details to the My Favourite list.
I have done the below code, which works perfectly fine if only one item is selected, but if multiple items are selected then the same item get added again and again.
var item=[];
var index=0;
var listItems = []
var context;
function getSelectedItems()
{
context = SP.ClientContext.get_current();
var listId = SP.ListOperation.Selection.getSelectedList(); //selected list Id
var selectedItemIds = SP.ListOperation.Selection.getSelectedItems(context); //selected Items Ids
var list = context.get_web().get_lists().getById(listId);
for (idx in selectedItemIds)
{
var itemID=selectedItemIds[idx].id;
listItems.push(selectedItemIds[idx].id);
}
for (index = 0; index < listItems.length; ++index)
{
item=null;
item = list.getItemById(listItems[index]);
context.load(item);
context.executeQueryAsync (Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
}
function onQuerySucceeded(sender, args) {
addToFavList();
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
function addToFavList()
{
var clientContext = new SP.ClientContext("/sites/somesite");
var oList = clientContext.get_web().get_lists().getByTitle('My Favourite');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', item.get_item("Document_x0020_Title"));
var Document_Number = new SP.FieldUrlValue();
Document_Number.set_url(item.get_item("Doc_x0020_Number").get_url());
Document_Number.set_description(item.get_item("Doc_x0020_Number").get_description());
oListItem.set_item("Document_x0020_Number", Document_Number);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onItemAddedSuccess),
Function.createDelegate(this, this.onItemAddedFailed));
}
function onItemAddedSuccess() {
alert('Item created: ' + oListItem.get_id());
}
Issue here is that, by the time Item is added the for loop continues and also by the time item details are fetched the item adding continues and hence it ends up in creating as many item as selected by the user but all the item in My Favourite contains same details.
Is there any way i can handle this issue? Adding items or fetching items Synchronously? I really dont know how to proceed. Kindly help.