Thursday 30 January 2014

Displaying Document Library with Folders along with documents and content using Ecma Script Client Object Model

ExecuteOrDelayUntilScriptLoaded(initDocument, "sp.js");


var docsCollection;
var currentcontext;
var folderURL='';
var listDocs;
var listDocRoot;


function initDocument()
{
    //under which folder currently are
    var hdnDocumentURL = $.jStorage.get("hdnDocumentURL");
   
    if(hdnDocumentURL == "null" || hdnDocumentURL==null)
    {
        getDocuments();
    }
    else
    {
        loadDocsFolderContents(hdnDocumentURL);
    }

}

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

function loadRootFolderDocumentContents()
{
    $.jStorage.set("hdnDocumentURL",null);
    getDocuments();
}


function loadDocsFolderContents(folderServerRelativeUrl)
{   
    //set current folder level
    $.jStorage.set("hdnDocumentURL",folderServerRelativeUrl);
   
    var folderStrcut='';
   
    //Split by comma
    var hashes = folderServerRelativeUrl.split('/');

    if (typeof (hashes) != 'undefined' && hashes != null) {
   
        folderStrcut="<a style=\"cursor:pointer;\" onclick=\"loadRootFolderDocumentContents();\"   title='Documents' >Documents</a>" ;
       
        //loop all folders, start from 7 to eliminate /sites/roost/Projects Home/projects_1320/Project Documents/Folder 1
        for (var i = 6; i < hashes.length; i++) {
            var folderName = hashes[i];
            var folderFullURLSplit=folderServerRelativeUrl.split(folderName);
            var folderFullURL=folderFullURLSplit[0] + folderName;

            folderStrcut=folderStrcut + " > " + "<a style=\"cursor:pointer;\" onclick=\"loadDocsFolderContents('" + folderFullURL + "');\"   title='" + folderName + "'>" + folderName+ "</a>" ;
        }
    }
   
    document.getElementById("DocumentsFolder").innerHTML = folderStrcut;
   
    var currentcontext = new SP.ClientContext.get_current();
    listDocs = currentcontext.get_web().get_lists().getByTitle('Project Documents');
    listDocRoot = listDocs.get_rootFolder();
      
    var camlQuery = new SP.CamlQuery();
   
    var spQuery= "<View Scope=\"RecursiveAll\"> " +
                    "<Query>" +
                    "<Where>" +
                                "<Eq>" +
                                    "<FieldRef Name=\"FileDirRef\" />" +
                                    "<Value Type=\"Text\">" + folderServerRelativeUrl + "</Value>" +
                                 "</Eq>" +
                    "</Where>" +
                    "</Query>" +
                    "</View>";
   
    //get list item by project ID
    camlQuery.set_viewXml(spQuery);

    docsCollection= listDocs.getItems(camlQuery);
   
    currentcontext.load(listDocs, 'Title', 'Id');
    currentcontext.load(listDocRoot);
    currentcontext.load(docsCollection, 'Include(ID,FileRef, FileLeafRef, Modified,FSObjType)');
    currentcontext.executeQueryAsync(Function.createDelegate(this, getDocumentsResult), Function.createDelegate(this, oncListQueryFailed));
}


function getDocuments() {
   
    document.getElementById("DocumentsFolder").innerHTML = '';

    //load site
    currentcontext = new SP.ClientContext.get_current();
    listDocs= currentcontext.get_web().get_lists().getByTitle('Project Documents');
       listDocRoot = listDocs.get_rootFolder();
      
    var camlQuery = new SP.CamlQuery();

    //get list item by project ID
    camlQuery.set_viewXml('<View><OrderBy><FieldRef Name=\'FSObjType\' Ascending=\'FALSE\' /></OrderBy></View>');

    docsCollection = listDocs.getItems(camlQuery);
   
    currentcontext.load(listDocs, 'Title', 'Id');
    currentcontext.load(listDocRoot);
    currentcontext.load(docsCollection, 'Include(ID,FileRef, FileLeafRef, Modified,FSObjType)');
    currentcontext.executeQueryAsync(Function.createDelegate(this, getDocumentsResult), Function.createDelegate(this, oncListQueryFailed));
}

function getDocumentsResult() {
    //re-create JQ Grid container
    $("#divDocumentsHolder").html('<div id=\'tblAllDocsPager\'></div><div id=\'divAllDocs\'></div>');
   
    var listID = listDocs.get_id();
    var listURL = listDocRoot.get_serverRelativeUrl();
   
    //Split by comma
    var hashes = listURL.split('Project_Documents');

    var listItemEnumerator = docsCollection.getEnumerator();
    var html = "";
    html = html + "<table id='tblAllDocs' border='0' cellspacing ='0' cellpadding='0'>";
    html = html + "<thead><tr><th>Type</th><th>FileName</th><th>Modified</th><th></th></tr></thead><tbody>";

    //loop the items
    while (listItemEnumerator.moveNext()) {

        //current item
        this.oListItem = listItemEnumerator.get_current();

        //get item details
        var itemOpenURL;
        var itemViewPropertiesURL;
        var fileURL = oListItem.get_item('FileRef');
        var fileName = oListItem.get_item('FileLeafRef');
        var fileDate = oListItem.get_item('Modified');
        var FSObjType=oListItem.get_item('FSObjType');
       
        var fileDateNew = (fileDate.getMonth() + 1) + "/" + fileDate.getDate() + "/" + fileDate.getFullYear();
       
        var values = fileURL.split('Lists');
        itemViewPropertiesURL= listURL  + '/Forms/DispForm.aspx?ID=' + oListItem.get_item('ID');
        itemOpenURL = fileURL + "?Web=1";
       
        var fileExt = fileName.split('.').pop();
        var fileImageURL;
       
        //SP folder
        if(FSObjType=='1')
        {
            fileImageURL='/_layouts/15/images/folder.gif?rev=23';
            html = html + "<tr><td style='text-align:center;'><img src='" + fileImageURL + "' / ></td><td>";
            html = html + "<div style=\"cursor:pointer;width:100%\" onclick=\"loadDocsFolderContents('" + fileURL + "');\"   title='" + fileName + "'>" + fileName+ "</div></td><td><nobr> " + fileDateNew + "</nobr></td><td><a class='viewall' target='_blank'  href='" + itemViewPropertiesURL + "' title='View properties'>View</a></td></tr>";
        }
        else
        {       
            if( fileExt == "pdf" ){   
                fileImageURL = "/_layouts/Images/IC" + fileExt + ".png";
            }
            else if(fileExt == 'onetoc2'){               
                fileImageURL = "/_layouts/Images/ICone.gif";
            }
            else {   
                fileImageURL = "/_layouts/Images/IC" + fileExt + ".gif";
                }
           
            //do not want to see .one files.....the actual One NoteBook is .onetoc2
            if(fileExt != 'one')  
            {                   
                //fileImageURL = "/_layouts/Images/IC" + fileExt + ".gif";
                html = html + "<tr><td style='text-align:center;'><img src='" + fileImageURL + "' / ></td><td>";
                html = html + "<a target='_blank'  href='" + itemOpenURL + "' title='" + fileName + "'>" + fileName+ "</a></td><td><nobr> " + fileDateNew + "</nobr></td><td><a class='viewall' target='_blank'  href='" + itemViewPropertiesURL + "' title='View properties'>View</a></td></tr>";
            }
        }      
    }

    html = html + "</tbody></table>";
    document.getElementById("divAllDocs").innerHTML = html;


    //under which folder currently are
    var hdnDocumentURL = $.jStorage.get("hdnDocumentURL");
   
    if(hdnDocumentURL == "null" || hdnDocumentURL == null)
    {
        hdnDocumentURL = listURL;
    }
   
    var createFolderURL=  listURL + "/Forms/Upload.aspx?RootFolder=" + hdnDocumentURL + "&Type=1&IsDlg=1";  
    var itemAddURL = hashes[0] + "_layouts/15/Upload.aspx?List={" + listID + "}&RootFolder="  + hdnDocumentURL + "&IsDlg=1" ;


    tableToGrid('#tblAllDocs',
                        { colNames: ['Type', 'FileName', 'Modified' , ''],
                            colModel: [
                        { name: 'Type', index: 'Type' , width:70 },
                        { name: 'FileName', index: 'FileName', width:260  },
                        {name: 'Modified', index: 'Modified', width: 100  },
                        { name: '', width:40  }
                                    ], 
                            width:  '100%',
                            height: 190,
                            caption: "<table cellspacing='0' cellpadding='0' width='100%'><tr><td style='width:69%'></td><td style='width:31%'><img title='new item' src='https://mcf1.sharepoint.com/sites/roost/siteAssets/images/plus.png' onclick=\"openRoostBoardDialog('"+itemAddURL+"');\" class='addNewImg' style='cursor:pointer;margin-left:10px;margin-right:10px;height:10px;width:10px;text-decoration:none' / ><span style='padding-top:10px'><img title='new folder' src='/_layouts/15/images/folder.gif?rev=23'  onclick=\"openRoostBoardDialog('"+createFolderURL+"');\"  style='cursor:pointer;'/ ></span><a class='AddNew' href='"+listURL+"' target='_blank' style='cursor:pointer;margin-left:10px;margin-right:10px;text-decoration:none;'><span class='AddNew'>View All</span></a></td></tr></table>",
                            pager: '#tblAllDocsPager',
                            rowNum: 8,
                            ignoreCase: true,
                            paging: true,
                            altRows: true,
                            altclass:'myAltRowClass',
                            emptyrecords: "No Documents",
                            viewrecords: true,
                            loadonce: true
                        });

    //Search
    $("#tblAllDocs").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: 'cn' });

    //For paging
    $("#tblAllDocs").jqGrid('setGridParam', {page: 1}).trigger("reloadGrid");

    //ExecuteOrDelayUntilScriptLoaded(getImages, "sp.js");
}

No comments:

Post a Comment