Friday, 10 January 2020

JSOM: How to display recent documents of current user using SharePoint search?


References

/bootstrap.min.css
/jquery.min.js
/jquery.SPServices.min.js
/bootstrap.min.js

Script

function loadDocuments()
{

var currUser = $().SPServices.SPGetCurrentUser({
fieldNames: ["WorkEmail"],
debug: false
});

currUser = currUser.split('p|')[1].split('@')[0];

var searchQuery = "https://ts.accenture.com/_api/search/query?querytext='*'&rowlimit=6&querytemplate='modifiedby:"+currUser+""+
" AND (FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf)'&sortlist='lastmodifiedtime:descending'&properties='ContentSetting:3'&selectproperties='Title,Path'";

  $.ajax({
    url: searchQuery,
    method: 'GET',
    headers: {
        'Accept': 'application/json; odata=verbose'
    },
    success: onQuerySuccess,
    error: onQueryFail
});

function onQuerySuccess(data) {
var docsHTML = "";
    var count=0;
try
{
    //OneDrive Documents
    try{
 
    if (data.d.query.SecondaryQueryResults.length == 0 || data.d.query.SecondaryQueryResults.results[0].RelevantResults.Table.Rows.results == 0)
    {
        //do nothing
    }
    else {
 
        $(data.d.query.SecondaryQueryResults.results[0].RelevantResults.Table.Rows.results).each(function() {
        count++;
if(count==4)
{
return false;
}
            var path = fetchValueForKey(this, 'Path');
            var title = fetchValueForKey(this, 'Title');
            path = path.replace(new RegExp(' ', 'g'), '%20');
            if(title.length>50)
            {
            title = title.substring(0,50);
            }
docsHTML += "<a href='"+path+"' target='_blank'>";
docsHTML += "<div class='media' style='height:25px;'>";
docsHTML += "<img src='https://ts.accenture.com/sites/afls/OnePSM/SiteAssets/onedrive.png' alt='' class='mr-1 mt-1' style='width:20px;'>";
docsHTML += "<div class='media-body'>";
docsHTML += "<p>"+title+"</p>";
docsHTML += "</div></div></a>";

        });

        //$('.spinner-grow').hide(); 
      }
      }
      catch(ex){}

//SharePoint Documents
try
{
    if ((data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results.length == 0)) {
        docsHTML = "<p>" + 'We were unable find your recent documents.' + "</p>";
    }
    else {
 
        $(data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results).each(function() {
        count++;
if(count==7)
{
return false;
}
            var path = fetchValueForKey(this, 'Path');
            var title = fetchValueForKey(this, 'Title');
            path = path.replace(new RegExp(' ', 'g'), '%20');
            if(title.length>50)
            {
            title = title.substring(0,50);
            }
docsHTML += "<a href='"+path+"' target='_blank'>";
docsHTML += "<div class='media' style='height:25px;'>";
docsHTML += "<img src='https://ts.accenture.com/sites/afls/OnePSM/SiteAssets/sharepoint.png' alt='' class='mr-1 mt-1' style='width:20px;'>";
docsHTML += "<div class='media-body'>";
docsHTML += "<p>"+title+"</p>";
docsHTML += "</div></div></a>";

        });

        $(docsHTML).appendTo('#documentsDiv');
        $('.spinner-grow').hide(); 
      }
    }
    catch(ex){}
    }
    catch(ex)
    {
    $('.spinner-grow').hide();
    }
}

function onQueryFail(sender, args) {
$('.spinner-grow').hide(); 
    //alert('Error:' + args.get_message());
}

function fetchValueForKey(row, fldName) {
    var val = null;
    $.each(row.Cells.results, function() {
        if (this.Key == fldName) {
            val = this.Value;
        }
    });
    return val;
}


HTML

<div class="col-sm-6 m-0">
<div class="card-header bg-info text-light">My Recent Documents</div>
    <div id="documentsDiv" class="card-body border pt-1" style="min-height:192px;">
    <div class="spinner-grow spinner-grow-sm text-primary"></div>
    <div class="spinner-grow spinner-grow-sm text-primary"></div>
    <div class="spinner-grow spinner-grow-sm text-primary"></div>
    <div class="spinner-grow spinner-grow-sm text-primary"></div>
</div>
</div>