Tuesday, December 8, 2015

Get next item ID from a SharePoint Document Library using REST

Environment: Using jQuery, REST, SharePoint 2013 Enterprise, knockout JS

Requirement: To get the next item ID from a SharePoint Document Library using REST

Prerequisite: knockout and latest jQuery are defined in the code.

Code:

function getNextSequenceID() {
              
var documentLibraryName = 'DocumentLibraryName';     
               var serverUrl = window.top._spPageContextInfo.webServerRelativeUrl;
              
               //Query the top 1 item sorted in descending order.
               var fileListItemIDUri = serverUrl + "/_api/web/lists/getbytitle('" + documentLibraryName + "')/items?$select=ID&$top=1&$orderby=ID%20desc";
               var sequenceID = 1;
                                            
                              return $.ajax({
                                             url: fileListItemIDUri,
                                             type: "GET",
                                             headers: { "accept": "application/json;odata=verbose" },
                                             success: function (data) {
                                             if(data.d.results.length==1)
                                             {
                                                            var id = data.d.results[0].ID;
                                                            sequenceID = id+1;
                                             }   
alert(“The next item ID is :”+ sequenceID);

        },
        error: function (data) {
        },
        });

};

Create a folder in a document library using REST

Environment: Using jQuery, REST, SharePoint 2013 Enterprise, knockout JS

Requirement: Create a folder in a document library with current year as the folder name using REST. Check if folder exists already, else create a new folder.

Prerequisite: knockout and latest jQuery must be defined.

Code:
var currentYear = ko.observable();
var documentLibraryName = “DocumentLibraryName”;   
var serverUrl = “http://webServerURL”;

//Following code should be executed on page load
self.currentYear = ko.computed(function () {
               currentYear = (new Date).getFullYear();
               return (new Date).getFullYear();
});

//fileUpload method is used to upload a file to a folder in SharePoint document library
self.fileUpload = function () {
self.doesFolderExist();
….
….
};

//doesFolderExist method is used to check if the folder already exists in the document library and create a new folder if does not exist.
self.doesFolderExist = function (){
                                            
              
               var fileCollectionEndpoint = serverUrl + "/_api/web/getfolderbyserverrelativeurl('" + documentLibraryName +"/"+currentYear+ "')";
               return $.ajax({
               url: fileCollectionEndpoint,
               type: "GET",                      
               headers: {
                              "accept": "application/json;odata=verbose",
                              "X-RequestDigest": window.top.$("#__REQUESTDIGEST").val()
                              },
                              success: function (data) {
                                             alert("Folder already exists");
                      },
               error: function (data) {
                              //Folder does not exist, so create a new folder
                              self.createFolder();
        }
});
};


//Create a folder in document library
self.createFolder = function ()
{
                             
               var fileCollectionEndpoint = serverUrl + "/_api/web/getfolderbyserverrelativeurl('" + documentLibraryName + "')/folders/add(url=\'" + currentYear + "\')";
                                            
               return $.ajax({
                              url: fileCollectionEndpoint,
                              type: "POST",
                              headers: {
                                             "X-RequestDigest":  window.top.$("#__REQUESTDIGEST").val(),
                                             "accept": "application/json;odata=verbose",
                                             "content-type": "application/json;odata=verbose"
                              },
                              success: function (data) {
                                             //alert(‘Folder created successfully’);
                                             },
                                              error: function (jqXHR, textStatus, errorThrown) {
                                                            //handle error...
                                                            alert('Failed to create folder in library.');
                                             }
                              });
               };

References: