I created a folder and have some item in this list. So now how can I move list item into folder using JSOM. I know user can drag/drop, but I want when user create a list is always move to folder automatically.
1 Answer
Example: how to move list item into a folder via SharePoint JSOM API
/**
* Move ListItem
* @param {SP.ListItem} list item
* @param {string} targetFolderUrl - server relative url of folder where listitem needs to be moved
*/
function moveListItem(listItem,targetFolderUrl,success,error){
var ctx = listItem.get_context();
ctx.load(listItem,['FileRef','FileDirRef']);
ctx.executeQueryAsync(
function(){
var fileUrl = listItem.get_item('FileRef');
var file = ctx.get_web().getFileByServerRelativeUrl(fileUrl);
var targetfileUrl = fileUrl.replace(listItem.get_item('FileDirRef'),targetFolderUrl);
file.moveTo(targetfileUrl, SP.MoveOperations.overwrite);
ctx.executeQueryAsync(success,error);
},
error);
}
Usage
var listTitle = "Requests";
var itemId = 1;
var targetFolderUrl = "/Lists/Requests/Archive";
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
moveListItem(item,targetFolderUrl,
function(){
console.log('List item has been moved');
},
function(sender,args){
console.log(args.get_message());
}
)