2

I am attempting to use JSOM to add a folder to a pre-created folder within a specified library. In the code below, I have checked that all of the variables are functioning as expected - meaning the library, the url, the arguments used as leaf names. However the query fails every time and I get the error "Value does not fall within specified range". The strange part is that if I attempt to add multiple folders, the first one is added, and the rest are dropped. Any help will be much appreciated.

function storeFolderTest() {
    var curLibrary = empLib;
    for (var i = 0; i < arguments.length; i++) {
        var folderURL = hostURL + "/" + "Employee Files" + "/" + "testFolder";

        var itemCreateInfo_subFolder = new SP.ListItemCreationInformation();
        itemCreateInfo_subFolder.set_underlyingObjectType(SP.FileSystemObjectType.folder);
        itemCreateInfo_subFolder.set_folderUrl(folderURL);
        itemCreateInfo_subFolder.set_leafName(arguments[i]);

        var oListItem2 = curLibrary.addItem(itemCreateInfo_subFolder);
        oListItem2.update();
    }
    context.load(oListItem2);
    context.executeQueryAsync(onQuerySucceeded, onQueryFailed);

    function onQuerySucceeded() {
        alert('folder uploaded');
    }

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

2 Answers 2

1

Instead of reusing the oListItem2 object for each new folder you want to create, try giving each new folder its own unique object. You can store them in an array like so:

function storeFolderTest() {
    var curLibrary = empLib;
    var newFolders = []; // <-- new array
    for (var i = 0; i < arguments.length; i++) {

        // ...

        newFolders.push(curLibrary.addItem(itemCreateInfo_subFolder));
        newFolders[i].update();
    }
    context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
1

The following worked for me. I didn't set the url like you are, just the leafname:

function storeFolderTest() {
    var curLibrary = empLib;
    var l = arguments.length;
    for (var i = 0; i < l; i++) {
        var newFolder = new SP.ListItemCreationInformation();
        newFolder.set_underlyingObjectType(SP.FileSystemObjectType.folder);
        newFolder.set_leafName(arguments[i]);

        var newItem = curLibrary.addItem(newFolder);
        newItem.update();
    }
    context.executeQueryAsync(onQuerySucceeded, onQueryFailed);

    function onQuerySucceeded() {
        console.log('folder created');
    }

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

Unless you plan to use the newly created item, you don't need to load it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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