How To Perform CRUD Operation On SharePoint Library Folders And Sub Folders Using SPServices And JavaScript

In this article lets see how to create, read, rename OOTB Folders in a SharePoint library programmatically using JQuery and SPServices

1. To create a Folder using SPServices,

function CreateFolder(folderName) {
     $().SPServices({
         operation: "UpdateListItems",
         async: false,
         listName: "Library Name",
         updates: "<Batch OnError='Continue' PreCalc='TRUE' ListVersion='0' >" +
               "<Method ID='1' Cmd='New'>" +
                  "<Field Name='FSObjType'>1</Field>" +
                  "<Field Name='BaseName'>" + folderName + "</Field>" +
                 "</Method>" +
                "</Batch>",
         completefunc: function (xData, Status) {
             console.log("Folder Created Successfully…");
         }
     });
 }

To create subfolder, the folderName value would be “ParentFolder/ChildFolder”.

2. To read the content inside the folder,

functionReadFolder(folderName) {
     $().SPServices({
         operation: "GetListItems",
         async: false,
         listName: "Library Name",
         CAMLViewFields: "<ViewFields Properties='True' />",
         CAMLQuery: "<Query><Where><Contains><FieldRef Name='FileRef' /><Value Type='Text'>"+ folderName + "</Value></Contains></Where></Query>",
         CAMLQueryOptions: "<QueryOptions><Folder>"+ folderName + "</Folder></QueryOptions>",
         completefunc: function(xData, Status) {
             $(xData.responseXML).SPFilterNode('z:row').each(function() {
                 itemID = $(this).attr("ows_ID");                         
                 //Extract other fields as per the requirement             
             });
         }
     });   
 }
If the content is inside the subfolder, then we need alter the above ReadFolder(folderName) function little bit
functionReadSubFolder(folderName, subfolder) {
 varfullFolderName = _spPageContextInfo.webServerRelativeUrl + "/Shared Document/"+ folderName;
 
     $().SPServices({
         operation: "GetListItems",
         async: false,
         listName: "Shared Document",
         CAMLViewFields: "<ViewFields Properties='True' />",
         CAMLQuery: "<Query><Where><Contains><FieldRef Name='FileRef' /><Value Type='Text'>"+ folderName + "</Value></Contains></Where></Query>",
         CAMLQueryOptions: "<QueryOptions><Folder>"+ fullFolderName + "</Folder></QueryOptions>",
         completefunc: function(xData, Status) {
             $(xData.responseXML).SPFilterNode('z:row').each(function() {
                 itemID = $(this).attr("ows_ID");
                 varsubFolderName = $(this).attr("ows_FileLeafRef").split(";#")[1];
                 if(subFolderName == subfolder) {
                     //use the same SPService in some other function and pass subfolder value
                 }
                 //Extact other fields as per your requirement
             });
         }
     });   
 }
3. To rename the specific folder,
functionRenameFolder(oldFolderName, newFolderName) {
     $().SPServices({
         operation: "GetListItems",
         async: false,
         listName: 'Library Name',
         CAMLViewFields: "<ViewFields Properties='True' />",
         CAMLQuery: "<Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where></Query>",
         CAMLQueryOptions: "<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns></QueryOptions>",
         completefunc: function(xData, Status) {
             $(xData.responseXML).SPFilterNode('z:row').each(function() {
                 varexistingFolderName = $(this).attr("ows_FileLeafRef").split(";#")[1];
                 if(existingFolderName == oldFolderName) {
                     varFolder_ID = $(this).attr("ows_ID");
                     $().SPServices({
                         operation: "UpdateListItems",
                         async: false,
                         batchCmd: "Update",
                         listName: 'Library Name',
                         valuepairs: [["Title", newFolderName], ["BaseName", newFolderName]],
                         ID: Folder_ID,
                         completefunc: function(xData, Status) {
                             console.log("Folder Name Updated Successfully...");
                         }
                     });
                 }
             });
         }
     });
 }
I would prefer JSOM to delete the folder, because it is an easy way to delete.
functionDeleteFolder(folderName) {
     clientContext = newSP.ClientContext.get_current();
     oWebsite = clientContext.get_web();
 
     clientContext.load(oWebsite);
     clientContext.executeQueryAsync(function() {      
         
         folderUrl = oWebsite.get_serverRelativeUrl() + "/Library Name/"+ folderName;
         this.folderToDelete = oWebsite.getFolderByServerRelativeUrl(folderUrl);
         this.folderToDelete.deleteObject();
 
         clientContext.executeQueryAsync(
             Function.createDelegate(this, successHandler),
             Function.createDelegate(this, errorHandler)
         );
     }, errorHandler);
 
     functionsuccessHandler() {
         console.log('Folder Deleted Successfully!!!');
     }
     functionerrorHandler() {
         console.log('Error in deleting the folder');
     }
 }
 SP.SOD.executeFunc("sp.js", 'SP.ClientContext', DeleteFolder('foldername'));
To delete the subfolder, we need to pass the folderName parameter along with the parent folder name delimited by ‘/’.

Leave a Reply

Your email address will not be published.