Sunday, 6 September 2020

How to filter JSON data to get value based on the supplied key?

 var existingData = [];


some-loop{

    existingData.push(
{
'email' : $(this).attr("ows_Email_x0020_ID"), //this will be the key
'id' : $(this).attr("ows_ID") // record id for a given email will be fetched
}
}


function getIDbyEmail(emailID)
{
try
{
//var obj; = existingData.filter(i=>i.email==emailID);

var obj = existingData.filter(function(item){
    return item.email == emailID;
});

var _id = obj[0].id;

if(_id == undefined || _id == "" || _id == null)
{
return 0;
}
else
{
return _id;
}
}
catch(err)
{
return 0;
}
}





Thursday, 20 August 2020

How to get current user information using SPServices?

 

currUser = $().SPServices.SPGetCurrentUser({

fieldNames: ["WorkEmail"], //Name (account name) is the default property

debug: false

});



currUserArr = $().SPServices.SPGetCurrentUser({

fieldNames: ["ID", "Name", "SIP Address"],

debug: false

});




Thursday, 13 August 2020

How to redirect SharePoint Home page to site contents page?

 

<script language="javascript" type="text/javascript">

document.addEventListener("DOMContentLoaded", function(){

  var url = location.href;

  location = url.replace("SitePages/test.aspx", "_layouts/viewlsts.aspx");

});

</script>

Wednesday, 12 August 2020

How to download SharePoint file, on click of its URL, instead of opening it in Chrome?

 

Use the OOB application page: download.aspx

https://server/sites/site/_layouts/download.aspx?SourceUrl=https://filepath/


Tuesday, 11 August 2020

How to search documents using SPServices and SharePoint Search?

 

var searchtext ="string to be searched";

SharePoint 2010:

var queryText = "<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'>";

queryText += "<Query>";

queryText += "<Context>";

queryText += "<QueryText language='en-US' type='MSSQLFT'>";

queryText += "SELECT SpSiteUrl, Title, Path, Description, HitHighlightedSummary, IsDocument";

queryText += "FROM Scope() WHERE FREETEXT(DEFAULTPROPERTIES, '";

queryText += searchtext;

queryText += "')And CONTAINS(Path, 'https://server/sites/site/subsite/library')";

queryText += "ORDER BY \"Rank\" DESC";

queryText += "</QueryText>";

queryText += "</Context>";

queryText += "<Range><Count>5000</Count></Range>";

queryText += "</Query>";

queryText += "</QueryPacket>";


SharePoint Online:

var queryText = "<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'>"

queryText += "<Query>"

queryText += "<Range><Count>500</Count></Range>";

queryText += "<Context>"

queryText += "<QueryText language='en-US' type='STRING'>"

queryText += searchtext;

queryText += " Site:https://server/sites/site/subsite/library/";

queryText += "</QueryText>"

queryText += "</Context>"

queryText += "</Query>"

queryText += "</QueryPacket>";


//declare required variables


$().SPServices({//sart service call

    operation: "Query",

    queryXml: queryText,

    async: false,

    completefunc: function (xData, Status) {

$(xData.responseXML).find('CopyResult').attr('ErrorMessage'));

        $(xData.responseXML).find("QueryResult").each(function () {

            var x = $(this).text();

            $(x).find("Document").each(function () {

                url = $("Action>LinkUrl", $(this)).text();

                if ((url.indexOf("site/subsite/library") > 0) && 

                    ((url.indexOf("aspx")) == -1)) {

title = $("Title", $(this)).text();

size = $("Action>LinkUrl", $(this)).attr('size');

ext = $("Action>LinkUrl", $(this)).attr('fileExt');

desc = $("Description", $(this)).text();

//clear/reset variables

                }

            });

        });


    }

});//end service call

Monday, 24 February 2020

JavaScript date : How to compare two dates to check which one is greater?


Example:

if(startDate.getTime() == endDate.getTime()) //both the dates are same
{
            //do something
}

JavaScript date : How to get days between two dates?


var daysInbetween = (d2.getTime() - d1.getTime())/(1000 * 3600 * 24);

JavaScript date : How to get all dates between two dates?


function getAllDatesBetween(startDate,endDate)
{
var d1 = new Date(startDate);
var d2 = new Date(endDate);
var d3;
var daysInbetween = (d2.getTime() - d1.getTime())/(1000 * 3600 * 24);

for(var i=0;i<=daysInbetween;i++)
{
d3 = new Date(d1);
d3.setDate(d3.getDate() + i);
datesArray.push((d3.getMonth()+1).toString()+"/"+d3.getDate().toString()+"/"+d3.getFullYear().toString());
}
}

JavaScript date : How to get month and year difference between two dates?


function yearsDiff(d1, d2) {
    var date1 = new Date(d1);
    var date2 = new Date(d2);
    var yearsDiff =  date2.getFullYear() - date1.getFullYear();
    return yearsDiff;
}

function monthsDiff(d1, d2) {
  var date1 = new Date(d1);
  var date2 = new Date(d2);
  var years = yearsDiff(d1, d2);
  var monthsDiff =(years * 12) + (date2.getMonth() - date1.getMonth()) ;
  return monthsDiff;
}

JavaScript date : How to get date for first, mid and last day of a month?


var firstDayStartDate = new Date(anyDateOfTheMonth.getFullYear(), anyDateOfTheMonth.getMonth(), 1);

var midDayStartDate = new Date(anyDateOfTheMonth.getFullYear(), anyDateOfTheMonth.getMonth(), 15);

var midDayPlusOneStartDate = new Date(anyDateOfTheMonth.getFullYear(), anyDateOfTheMonth.getMonth(), 16);

var lastDayStartDate = new Date(anyDateOfTheMonth.getFullYear(), anyDateOfTheMonth.getMonth() + 1, 0);

JavaScript Date : How to get working hours between two dates?


function getWorkingHoursBetween(d1,d2)
{
var workingDays = 0;
var daysInbetween = (d2.getTime() - d1.getTime())/(1000 * 3600 * 24);
var d3, iDay;
for(var i=0;i<=daysInbetween;i++)
{
d3 = new Date(d1);
d3.setDate(d3.getDate() + i);
iDay = d3.getDay();
if(iDay !=0 && iDay!=6)
{
workingDays++;
}
}
return (workingDays*9); //9 being the working hours per day
}

w2ui Form : How to validate a form?


actions: {
            reset: function () {
                this.clear();
            },
            save: function () {
                var errorList = w2ui['formName'].validate();
                if(errorList.length==0)
                {
                saveFormDataCustomFunction();
                }
            }
        }

w2ui Form : How to update a field on change of another field?


Form: 

onChange: function (event)
{
if(event.target=="fieldName1")
{
event.done(function () {
$('input[type=fieldName2]').w2field('list',
{
items: getFilteredValuesArray
}
);
});
}
if(event.target=="ResourceID")
{
event.done(function () {
refreshCalendar();
});
}
if(event.target=="Start Date")
{
event.done(function () {
refreshCalendar();
});
}
}


Function:

function refreshCalendar()
{
setUnavialableDatesForResource(w2ui['formName'].get('ResourceID').el.value);
$('input[type=start-date]').w2field('date',
{
format: 'm/d/yyyy',
blocked: blockedStartDates
}
);

setUnavialableEndDatesForResource(w2ui['formName'].get('Start Date').el.value);
$('input[type=end-date]').w2field('date',
{
format: 'm/d/yyyy',
blocked: blockedEndDates
}
);
}

HTML:
<input name="Start Date" type="start-date"/>
<input name="End Date" type="end-date"/>

w2ui Form : How to get and set a field's value?


Get:

var val = w2ui['formName'].get('fieldName').el.value;

OR

var val = $("fieldName").val


Set:

$("fieldName").val = "New Value";

OR

w2ui['formName'].get('fieldName').el.value = "New Value";

Thursday, 20 February 2020

How to show/hide section in an InfoPath form on click of a button?

Create (hidden) fields for each section and change/toggle the value on click of button as per the requirement.

Set a formatting rule for each section, which will show/hide the section based on the hidden fields values.

You can set a default values for the above variables based on the requirement.

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>