Thursday, August 4, 2016

Retrieve Query String Value from Sharepoint using Javascript

If you want to retrieve the values passed via Query String from a SharePoint URL , please use the below function . You can add it to any script editor , content editor web parts or visual web parts .


For example , I have a Query String say ID, and I want the value passed to it , I can call my method as follows.


<script>
$(document).ready(function() {
var ID= getParameterByName('ID'); 
//ID will return the Query string value
alert(ID);
});






function getParameterByName(name,url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


</script>

Check If current User member of Sharepoint Group using JSOM (2013 or 2010)

The following block of code will help you identify if the current logged in user is already a part of any SharePoint group .


Say for example, I need to check if the current user belongs to Elninos Football Team SharePoint group .  You can use the following scripts in script web parts, content editor web parts, or visual web parts.


Please see the code below:

<script>
// Provide the Group name
var grpName="Elninos Football Team";
$(document).ready(function() {

 ExecuteOrDelayUntilScriptLoaded(IsCurrentUserMemberOfGroup, "sp.js");
 
});
     
  });
//Ready function ends

function IsCurrentUserMemberOfGroup()
{
       
        var userInGroup;
        var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();    
        var currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);
        var allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);
        currentContext.load(allGroups, 'Include(Users)');
        currentContext.executeQueryAsync(OnSuccess,OnFailure);
       
  
        function OnSuccess(sender, args) {
            var userInGroup = false;
          
            var groupEnumerator = allGroups.getEnumerator();
            while (groupEnumerator.moveNext() && !userInGroup)
            {
               var oGroup = groupEnumerator.get_current();
               if (oGroup.get_title() ==  grpName )
               {
                  var collUser = oGroup.get_users();
                  var userEnumerator = collUser.getEnumerator();
                  while (userEnumerator.moveNext() && !userInGroup)
        {
                  var oUser = userEnumerator.get_current();
                  if (oUser.get_id() == currentUser.get_id())
                   {
                    userInGroup = true;
                    alert("User is a member of the Group you have given");
                   }
                   }
                }
            }
       }
        function OnFailure(sender, args) {
  alert("User not found");
        }      
}
</script>

Wednesday, September 9, 2015

Read user profile Information in sharepoint 2013 and JSOM

Requirement : Read user profile Information in  sharepoint 2013 and JSOM?


Steps to do it :
1.  Create a new page in sharepoint 2013 "UserProfiletest.aspx"
2. Add a script editor webpart to it.
3. Add references to jquery library and sp.js  in the script tag
4. Paste the following code in the script editor webpart .


<script>
 $(document).ready(function () {
            siteUrl = _spPageContextInfo.webServerRelativeUrl;
            GetLoadVision();
        });




        function GetLoadVision() {
           //load sp.js
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
        }




function retrieveListItems(){
var userID="domain/username";
getUserProfile(userID);
}

function getUserProfile(userID)
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var userInfoList = web.get_siteUserInfoList();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' +'<Value Type=\'Number\'>' + userID + '</Value></Eq' +'</Where></Query><RowLimit>1</RowLimit></View');
this.collListItem = userInfoList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
var item = collListItem.itemAt(0);
var profile = item.get_item(‘Notes’);
var pictureUrl = item.get_item(‘Picture’).get_url();
var userImage = document.getElementById(‘myImageContainer’); -> Image object
userImage.src = pictureUrl;
var profileDiv = document.getElementById(‘userProfileContainer’);
profileDiv.innerHTML = profile;
}


</script>


<div id="userProfileContainer’"></div>


That's it... :)

Friday, August 1, 2014

Color Code/replace with images a SharePoint List Column Value in Sharepoint 2013- The outstanding JS link property to the rescue

Wondering how to color code a sharepoint list column based on its value.
You have come to the right page here.. congrats..

Requirement: I have a list called colour code. Now I have a column named Active , which stores Yes or No values.




I need to show ticks for all Yes values and Cross for all No. how will i Do it?


JS Link to the rescue.
1 .Go to your Display Form, open the page in edit mode
2. Now in the webpart properties , go to Miscellaneous tab reference the link to a JS file called Colors.js
Put the following in the JS Link proerty "~sitecollection/style Library/colors.js"

3.  Now just paste the following code in Colors.js  file and upload it to the Style Library of the site.
Note: give  your site collection url in the image tag


(function () {     var statusFieldCtx = {};     statusFieldCtx.Templates = {};     statusFieldCtx.Templates.Fields = {     "Active"://Name of the column for which images needs to be displayed
  {     "View": StatusFieldViewTemplate     }
};     SPClientTemplates.TemplateManager.RegisterTemplateOverrides(     statusFieldCtx     ); })(); function StatusFieldViewTemplate(ctx) {     var _statusValue = ctx.CurrentItem.Active; // Active is the column name    if (_statusValue == 'Yes')     {
        return "<img src=SiteCollectionURL/style%20library/tick.png'/>";         } if (_statusValue == 'No') {     return "<img src= SiteCollectionURL /style%20library/cross.png'/>"; } }


4. that’s it and you are done.. Now just go to the list and refresh your page. See the magic your self:

Friday, April 4, 2014

How to hide the Site Contents link from Quick Launch for all the pages across the sites in sharepoint 2013

If you want this to be done for all the pages in teh site .. you must implement it via the master page ..

This would ensure that it is hidden from all the pages

we are goind to use jquery . Create a js file in teh layouts folder. and paste the following code in it .

$(document).ready(function(){

$('a[href$="/_layouts/15/viewlsts.aspx"]').each(function()

{ $(this).hide(); });

});

Now in the master page please refer to the js file as shown below in the layouts before the close of body tag.

"script type="text/javascript" src="_layouts/15/customjsfile.js"

Tuesday, March 11, 2014

How to get the site collection URL in the masterpage of a SharePoint 2013 site or subsites using Javascript in masterpage

There might be times when you really want to get the URL of the site collection within the master page of sharepoint 2013 sites.

well you can achieve it by using the below javascript line .

Inorder to add script in masterpage , we have to follow the conventional and well known method of the script tag inside the body of HTML.

now within the script tag just copy paste the following function

function getSiteCollectionsURL()

{

var sitecollectionURL = window.location.protocol + "//" + window.location.host +_spPageContextInfo.siteServerRelativeUrl

return sitecollectionURL;

}

the function can be called from anywhere inside the masterpage according to your needs.. it will return the site collection url no matter where you are , ie , whether you are in the subsite or the site collection or the nested subsite.

Thursday, March 6, 2014

Read a list column value using SP services in SharePoint

How can i read  a column value value of a share point list using Jquery and SP services

This can be achieved by the following java script function .

Make sure in your JS page you have refered the jquery and spservices link
//read the tiltle field value of ABC list
function ReadColumnValue()
{

var myvalue=null;
var strViewfields = "<ViewFields><FieldRef Name='Title'/></ViewFields>";
$().SPServices({
webURL: strSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "ABC",

            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
               
if($(this).attr("ows_title")!= undefined)
{

       myvalue=$(this).attr("ows_title");


}
                });
            }

        });



the variable myvalue will containt eh list column value of the tilte field of the AB list




Rename a Web Application in Sharepoint : A solution using powershell

Here is a small script that will enable you all to change a SharePoint Web Application name . We can use the following SharePoint Pow...