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,
 function ReadFolder(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
 function ReadSubFolder(folderName, subfolder) {
 var fullFolderName = _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");
                 var subFolderName = $(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,
 function RenameFolder(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 () {
                 var existingFolderName = $(this).attr("ows_FileLeafRef").split(";#")[1];
                 if (existingFolderName == oldFolderName) {
                     var Folder_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.
 function DeleteFolder(folderName) {
     clientContext = new SP.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);
 
     function successHandler() {
         console.log('Folder Deleted Successfully!!!');
     }
     function errorHandler() {
         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 ‘/’.
Happy Coding
Ahamed

Leave a comment