Friday, 1 July 2016

Query String Passing in Sharepoint Hosted App in Javascript



Pass Querystring value from SharePoint Page to App Part(Client web part)

As we know an App Part generates an Iframe when it is added into a SharePoint page, so we face difficulty to pass query string value from page to app part.
Here is the simple way to handle this. Using below information we can pass information from SharePoint page/webpart to our app part.
Step 1: 
In your App part go to element.xml file and add one dummy property which you only be using to pass Query string values. Keep Property name same as Query String Name as shown below:
AppProperty
Step 2: On your page where you have added App part, add a script editor or content editor web part just below the app part and add below script:
<script>
var arrFrames = document.getElementsByTagName(“iframe”);
for(i = 0; i< arrFrames.length; i++)
{
var iFrame=arrFrames[i];
var clientID=”QueryStringIDValue”;
if(iFrame.src.indexOf(clientID) != -1)
{
alert();
var queryStringValue=getQuerystring(‘QueryStringID’);
if(queryStringValue != null)
{
iFrame.src=iFrame.src.replace(clientID,queryStringValue);
}
}
}
function getQuerystring(key)
{
key = key.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);
var regex = new RegExp(“[\\?&]”+key+”=([^&#]*)”);
var qs = regex.exec(window.location.href);
if(qs == null)
return null;
else
return qs[1];
}
</script>
Above code will find out all the iframes and see where the QueryStringIDValue exists on scr of each Iframe as shown in below figure and replace with QueryString value of the page:
Here is the iframe generated by the app part from the page view source:
IframeViewPage
Our JavaScript will replace the property value with the query string value and the query string value can be used within app page load.

Get the Passed value into Our Page

Way of getting value:

 sponsorItemID = GetParameterValues("SponsorItemID");

Passing parameter to the function
 
function GetParameterValues(param) {
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0] == param) {
            return urlparam[1];
        }
    }
}
   

Adding app part properties in SharePoint 2013 hosted apps

 <!-- Content element identifies the location of the page that will render inside the client web part
         Properties are referenced on the query string using the pattern _propertyName_
         Example: Src="~appWebUrl/Pages/ClientWebPart1.aspx?Property1=_property1_" -->

      <Content Type="html" Src="~appWebUrl/Pages/SponsorApplication.aspx?{StandardTokens}&amp;SponsorTitle=_SponsorTitle_&amp;SponsorItemID=_SponsorItemID_&amp;SponsorHistoryUrl=_SponsorHistoryUrl_&amp;SponsorHistoryUrl=_SponsorHistoryUrl_"  />

      <!-- Define properties in the Properties element.
         Remember to put Property Name on the Src attribute of the Content element above. -->
   
 <Properties>

      <Property Name="SponsorTitle" Type="string" RequiresDesignerPermission="true" DefaultValue="Sponsor" WebBrowsable="true" WebDisplayName="Sponsor Title" WebDescription="Sponsor_Title" WebCategory="Sponsor Properties" />

      <Property Name="SponsorItemID" Type="string" RequiresDesignerPermission="true" DefaultValue="" WebBrowsable="true" WebDisplayName="Sponsor Item Id" WebDescription="Sponsor_Item_Id" WebCategory="Sponsor Properties" />

      <Property Name="SponsorHistoryUrl" Type="string" RequiresDesignerPermission="true" DefaultValue="" WebBrowsable="true" WebDisplayName="Sponsor History Url" WebDescription="Sponsor_History_Url" WebCategory="Sponsor Properties" />

    </Properties>

Getting Current User Permission in list Item

//Common Method for Getting Current User Permission in list Item

//Parameters Required
//1)AppwebUrl
//2)HostWebUrl
//3)ListName
//4)Listem Id
//5)Callback

//for calling function use GetItemPermissions({AppwebUrl},{HostWebUrl},{ListName},{Listem Id},function(data){
//alert(data);
//});

//sample
//GetItemPermissions(SPAppWebUrl,SPHostUrl,"Save List",41,function(data){
//alert(data);
//});


 
    function getListUserEffectivePermissions(AppWebUrl, HostURL, listTitle, accountName, ItemID, callback) {
        var endpointUrl = AppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/items(" + ItemID + ")/getusereffectivepermissions(@u)?@u='" + encodeURIComponent(accountName) + "'&@target='" + HostURL + "'";
        $.getJSON(endpointUrl).done(function(data) {
            callback(data);
        }).fail(function(data) {
            console.log(data);
            callback("error")
        });
    }

    function parseBasePermissions(value) {
        var permissions = new SP.BasePermissions();
        permissions.initPropertiesFromJson(value);
        var permLevels = [];
        for (var permLevelName in SP.PermissionKind.prototype) {
            if (SP.PermissionKind.hasOwnProperty(permLevelName)) {
                var permLevel = SP.PermissionKind.parse(permLevelName);
                if (permissions.has(permLevel)) {
                    permLevels.push(permLevelName);
                }
            }
        }
        return permLevels;
    }

    function GetItemPermissions(AppWebUrl, HostURL, ListName, ItemID, callback) {
        $.getJSON(AppWebUrl + "/_api/SP.AppContextSite(@target)" + "/web/currentuser?@target='" + HostURL + "'").done(function(data) {
            Email = data.LoginName;
            getListUserEffectivePermissions(AppWebUrl, HostURL, ListName, Email, ItemID, function(data) {
                if (data != "error") {
                    var roles = parseBasePermissions(data);                   
                    callback(roles);
                } else {
                    callback("Error");
                }
            });
        }).fail(function(data) {
            console.log(data);
            callback("Error");
        });
    }

Save, Update & Delete function using REST Services in Hosted App

   //Common script for adding and updating list item
   //Paramaters Required
   //1) AppWebUrl
   //2) HostUrl
   //3) Listname
   //4) Metadata of List item to be saved
   //5) Item Id to be updated
   //For Save call function as below
   //saveitem(AppWebUrl,HostUrl,listName,metadata,function(ItemId,data)
   //{
   //ItemId -->Saved/Updated Item Id, Returns 0 if error
   //Data -->success data
   //});
   //for update call function as below
   // UpdateItem(AppWebUrl,HostUrl,listName,metadata,ItemIdtobeupdated,function(ItemId,data)
   //{
   //ItemId -->Saved/Updated Item Id, Returns 0 if error
   //Data -->success data
   //});
  
   //DeleteItem(AppWebUrl, HostWebUrl, ListName,ItemId,function(Success,data)
   //{
   //Success --> returns 0--> If Error or ItemId--> If Success
   //Data -->success data
   //});
   function saveitem(e, t, o, n, a) {
       var Saveexecutor = new SP.RequestExecutor(e);
       var r = e + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + o + "')/items?@target='" + t + "'";
       Saveexecutor.executeAsync({
           url: r,
           method: "POST",
           body: n,
           headers: {
               "content-type": "application/json; odata=verbose",
               accept: "application/json;odata=verbose"
           },
           contentType: "application/json",
           success: function(e) {
               var t = JSON.parse(e.body);
               a(t.d.Id,e)
           },
           error: function(e) {
               console.log(JSON.stringify(e.body)), a(0,e)
           }
       })
   }

   function UpdateItem(e, t, o, n, a, r) {
       var Saveexecutor = new SP.RequestExecutor(e);
       var c = e + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + o + "')/items(" + a + ")?@target='" + t + "'";
       Saveexecutor.executeAsync({
           url: c,
           method: "POST",
           body: n,
           headers: {
               Accept: "application/json;odata=verbose",
               "content-type": "application/json;odata=verbose",
               "X-HTTP-Method": "MERGE",
               "IF-MATCH": "*"
           },
           contentType: "application/json",
           success: function(e) {
               r(a,e)
           },
           error: function(e) {
               console.log(JSON.stringify(e.body)), r(0,e)
           }
       })
   }
  
   function DeleteItem(AppWebUrl, HostWebUrl, ListName,ItemId, callback) {
       
        var Saveexecutor = new SP.RequestExecutor(AppWebUrl);
       var c = AppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + ListName + "')/items(" + ItemId + ")?@target='" + HostWebUrl + "'";
       Saveexecutor.executeAsync({
           url: c,
           method: "POST",
           headers: {
               Accept: "application/json;odata=verbose",
               "content-type": "application/json;odata=verbose",
               "X-HTTP-Method": "DELETE",
               "IF-MATCH": "*"
           },
           contentType: "application/json",
           success: function(data) {
               callback(ItemId,data)
           },
           error: function(data) {
               console.log(JSON.stringify(data.body)), callback(0,data)
           }
       })
    }

Making Active and InActive fields based on Condition

Here Call this function with boolean parameter and set it to respected field id's

function ActiveAndInActive(noneditableChoice) {
    try{
      
        document.getElementById("sponsorCode").readOnly = true;
        document.getElementById("sponsorName").readOnly = noneditableChoice;
        document.getElementById("sponsorAddress").readOnly = noneditableChoice;
        document.getElementById("sponsorActive").disabled = noneditableChoice;
        document.getElementById("primarySponsorContactName").readOnly = noneditableChoice;
        document.getElementById("primarySponsorContactNumber").readOnly = noneditableChoice;
        document.getElementById("primarySponsorEmail").readOnly = noneditableChoice;
        document.getElementById("secondarySponsorContactName").readOnly = noneditableChoice;
        document.getElementById("secondarySponsorContactNumber").readOnly = noneditableChoice;
        document.getElementById("secondarySponsorEmail").readOnly = noneditableChoice;
        $('#saveButton').attr("disabled", noneditableChoice);
    }
    catch (errorMsg) {
        console.log(errorMsg.message);
    }
}

Dynamic field validation 

 <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>
 
  // When the browser is ready...
  $(function() {
 
    // Setup form validation on the #register-form element
    $("#register-form").validate({
   
        // Specify the validation rules
        rules: {
            firstname: "required",
            email: {
                required: true,
                email: true
            },
           
            password: {
                required: true,
                minlength: 5
            },
             'test[]': {
                required: true,
                maxlength: 2
            },
            agree: "required",
            duration :"required",
           
        expanded :"required",
        projecttype:"required"
       
   
           
        },
       
        // Specify the validation error messages
        messages: {
            firstname: "Please enter your first name",
            lastname: "Please enter your last name",
            password: {
                required: "Please provide your feedback",
                minlength: "Your feedback must be at least 60 characters long"
            },
            contentarea : {
                 required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            },
             'test[]' : {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            },
            email: "Please enter a valid email address",     
            expanded  : "Please enter expanded character attributes",
            selected : "Select anyone field",
            projecttype : "Please select the project type",
            dates: "myselect",
            duration :"Please enter your duration"
       
        },
       
         highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
            $(element).closest('.datetimepicker').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
             $(element).closest('.datetimepicker').removeClass('has-error');
        },
       
        submitHandler: function(form) {
            form.submit();
        }
    });

  });
 
  </script>

CallBack Function Usage in Javascript in Hosted App


Main Function to call for CallBack

function checkDuplicates(projectCode, callback) {
    var url = appWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + projectListName + "')/items?$select=ProjectCode&$filter=ProjectCode eq '" + projectCode + "'&@target='" + hostWebUrl + "'";
    var IsDuplicate = false;
    var executor = new SP.RequestExecutor(appWebUrl);
    executor.executeAsync({
        url: url,
        method: "GET",
        headers:
            {
            "accept": "application/json;odata=verbose"
        }, contentType: 'application/json',

        success: function (data)
        {
            var jsonObject = JSON.parse(data.body);
            var object = jsonObject.d.results
            if (object.length > 0)
            {
                IsDuplicate = true;
            }
            callback(IsDuplicate);
        },
        error: function (errorData) { console.log(errorData.message); }
    });
}

Way of calling the CallBack function 
 
checkDuplicates(enteredProjectCode, function (data)

Multiple Field Validation Check Using JavaScript

Keep it in a function
Get values from the fields and Check with boolean values

try{
        var spName = $('#sponsorName').val();
        var spCode = $('#sponsorCode').val();
        var psContactName = $('#primarySponsorContactName').val();
        var psContactNumber = $('#primarySponsorContactNumber').val();
        var psEmail = $('#primarySponsorEmail').val();
        var ssEmail = $('#secondarySponsorEmail').val();
        var ssContactNumber = $('#secondarySponsorContactNumber').val();
        var valid = true;



      
        if (spName) {
            $("#sponsorNameId").css("display", "none");
            $("#sponsorName").parent().removeClass("has-error");
           
              
            }
            else {
                $("#sponsorNameId").show();
                $("#sponsorNameId").text(errSponsorNameRequired);
                $("#sponsorName").parent().addClass("has-error");
                valid = false;
            }
       

        if (spCode) {
           

            $("#sponsorCodeId").css("display", "none");
            $("#sponsorCode").parent().removeClass("has-error");
           

            }
        else {
            $("#sponsorCodeId").show();
            $("#sponsorCodeId").text(errSponsorCodeRequired);
            $("#sponsorCode").parent().addClass("has-error");
            valid = false;
            }

       
        if (psContactName) {


            $("#primarySponsorContactNameId").css("display", "none");
            $("#primarySponsorContactName").parent().removeClass("has-error");
           
               
            }
            else {
                $("#primarySponsorContactNameId").show();
                $("#primarySponsorContactNameId").text(errPrimarySponsorContactNameRequired);
                $("#primarySponsorContactName").parent().addClass("has-error");
                valid = false;
            }

       
        var numberValid = /^(?=.*[0-9])[- +()0-9]+$/;
        if (psContactNumber && psContactNumber.match(numberValid))
        {
          
                $("#primarySponsorContactNumberId").css("display","none");
                $("#primarySponsorContactNumber").parent().removeClass("has-error");
             
        }
        else {

            $("#primarySponsorContactNumberId").show();
            $("#primarySponsorContactNumberId").text(errPrimarySponsorContactNumberRequired);
            $("#primarySponsorContactNumber").parent().addClass("has-error");
            valid = false;
        }

        var emailvalid = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;



        if (psEmail && psEmail.match(emailvalid)) {

         
            $("#primarySponsorEmailId").css("display", "none");
                $("#primarySponsorEmail").parent().removeClass("has-error");
              
         
           
        }
        else {
            $("#primarySponsorEmailId").show();
            $("#primarySponsorEmailId").text(errPrimarySponsorEmailRequired);
            $("#primarySponsorEmail").parent().addClass("has-error");
            valid = false;
        }
       

        if (ssEmail) {

            if (ssEmail.match(emailvalid)) {
                $("#secondarySponsorEmailId").css("display", "none");
                $("#secondarySponsorEmail").parent().removeClass("has-error");
              
            }
            else
            {
                $("#secondarySponsorEmailId").show();
                $("#secondarySponsorEmailId").text(errSecondarySponsorEmail);
                        $("#secondarySponsorEmail").parent().addClass("has-error");
                        valid = false;
            }
        }
       
      

        if (ssContactNumber) {

            if (ssContactNumber.match(numberValid)) {
                $("#secondarySponsorContactNumberId").css("display", "none");
                $("#secondarySponsorContactNumber").parent().removeClass("has-error");
              
            }
            else {

                $("#secondarySponsorContactNumberId").show();
                $("#secondarySponsorContactNumberId").text(errSecondarySponsorContactNumber);
                $("#secondarySponsorContactNumber").parent().addClass("has-error");
                valid = false;
            }
        }
        return valid;
    }
    catch (errorMsg) {
        console.log(errorMsg.message);
    }