Thursday, February 9, 2017

Display Files / Folders from a Document Library in Sharepoint

Below is the code to display documents / folders from a library in a Sharepoint environment, in a Tree View.

we are using SPServices and JQuery to achieve this  functionality.

 <div id='status' style='color:#d41414;display:none;padding:5px'>  
 </div>  
 <div id='main-block' style='display:none'>  
      <div><h3>Documents</h3></div>  
      <div id="0">  
      </div>  
 </div>  
 <script src="/InternalResources/jquery.min.js"></script>  
 <script src="/InternalResources/jquery.SPServices-0.7.2.min.js"></script>  
 <script language="javascript" type="text/javascript">  
 $(document).ready(function(){  
      //Enter the list name. If url is different, please update url variable too.  
      //Here code takes the current context and current website  
   var list = "TestFolders";  
   var url = list + "/";   
      createTree(url, 0, list);       
  });  
 function createTree(url, tagID, list){  
   //get the url to define the level of tree,  
   $().SPServices({  
   operation: "GetListItems",  
   async: false,  
   listName: list,  
   CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='EncodedAbsUrl' /></ViewFields>",  
   CAMLQueryOptions: "<QueryOptions><Folder>" + url + "</Folder></QueryOptions>",  
   completefunc: function (xData, Status) {  
           if($(xData.responseXML).SPFilterNode("z:row").length > 0) {  
                $("#"+tagID+"").append("<ul id='prime-"+tagID+"'>");  
                $(xData.responseXML).SPFilterNode("z:row").each(function() {  
                     var id = $(this).attr("ows_ID");  
                     var title = $(this).attr("ows_Title");     
                     var folder =  $(this).attr("ows_FileLeafRef").split(";#")[1];   
                     $("#prime-"+tagID+"").append("<li id='"+id+"'>" + " <a href='"+$(this).attr("ows_EncodedAbsUrl")+"'>" + folder + " </a></li>");                  
                 var thisFSObjType = $(this).attr("ows_FSObjType").split(";#")[1];  
                 if(thisFSObjType == 1) {  
                     //auto call the function createTree again, to get subfolders and files, assigning a new url/subfolder and id  
                     createTree(url+'/'+folder, id, list);       
                 }  
                 });  
                 $("#"+tagID+"").append("</ul>");  
                 $('#status').css('display','none');  
                 $('#main-block').css('display','block');  
           }  
           else     {  
                $('#status').html('No documents found.');  
                $('#status').css('display','block');  
           }  
      }  
  });   
 }  
 </script>  

No comments:

Post a Comment