Solved

Check if Current user exist in sharepoint group in a site

Posted on 2013-05-18
5
3,250 Views
Last Modified: 2014-04-01
I have multiple permission groups created on the site and I have a form displaying the drop down list of the group names. This is a choice field.

Before submitting the form, I would like to check if the current user , based on whatever he selects in the dropdownlist, I would like to check if the user exist in that group before the user clicks the submit.

I have the folowing code to find  the current user on the SP site. But i dont know how to modify the code to find if the current user exist in the permission group?  

<script type="text/javascript" language="javascript">
var context = null;
    var web = null;
    var currentUser = null;
    function getWebUserData() {
        context = new SP.ClientContext.get_current();
        web = context.get_web();
        currentUser = web.get_currentUser();
        currentUser.retrieve();
        context.load(web);
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
    }
    function onSuccessMethod(sender, args) {
        var userObject = web.get_currentUser();
        alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());
    }
    function onFailureMethod(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");
    </script>
PLease help.
0
Comment
Question by:ven1234
  • 2
  • 2
5 Comments
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 39178461
Hi,
perhaps the usage of SPServices would make this easier:
http://morshemesh.blogspot.de/2012/07/getting-all-groups-of-user-with.html

HTH
Rainer
0
 

Author Comment

by:ven1234
ID: 39206691
Hi,
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var groupName;

 $().SPServices({  
      operation: "GetGroupCollectionFromUser",  
      userLoginName: $().SPServices.SPGetCurrentUser(),  
      async: false,  
      completefunc: function(xData, Status) {
        //if current user is not a member of this group...  
        if($(xData.responseXML).find("Group[Name=' a group"]").length != 1)  
        {  
              //...disable the following fields
             alert("Please check the activity you have selected");
             $("input[Title='btnSave']").prop("disabled", "disabled");
              }  
      }  
    });  
});

</script>

The above code works if i have find for 1 group.  But based on the drop down selection, I have to check if that user exist in that group.  Can you please guide me on how to write that code?.
0
 

Author Comment

by:ven1234
ID: 39206696
Something like this
isGroupMember("myGroupName", function(result){
if(result){
//code here
}
});

function isGroupMember(groupName, callback)
{
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: true,
completefunc: function(xData, Status) {
callback( !!($(xData.responseXML).find("Group[Name='" + groupName + "']").length) ); /* returns bool */
}
});
};

I have an drop down field and based on the field selected, I have to assign that value to a variable and that variable needs to be accessed as groupName.

Please help to rewrite the code.
0
 
LVL 44

Accepted Solution

by:
Rainer Jeschor earned 500 total points
ID: 39213559
Hi,
as I have not your full page source, I did a small PoC:
<div id="workingarea">
<select id="groupselection">
	<option value="">Please select</option>
	<option value="EE Testing Members">Members</option>
	<option value="EE Testing Visitors">Visitors</option>
	<option value="EE Testing Owners">Owners</option>
	<option value="TestDummy1">TestDummy1</option>
	<option value="TestDummy2">TestDummy2</option>
</select>
</div>
<p></p>
<div id="debugbox">
Debug messages:<br/>
</div>
<!-- Begin Javascript and JQuery -->
<script type="text/javascript" src="/_layouts/RainerJScripts/jquery-1.8.3.min.js" language="javascript"></script>
<script type="text/javascript" src="/_layouts/RainerJScripts/jquery.SPServices-0.7.2.min.js" language="javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	// Gets the current sites URL
	var currSiteUrl = $().SPServices.SPGetCurrentSite();
	$("#debugbox").append('Current site url: ' + currSiteUrl +'<br/>');
	// Gets the current user
	var currUser = $().SPServices.SPGetCurrentUser();
	$("#debugbox").append('Current user: ' + currUser+'<br/>');	

	// If group name selection has changed
	$("#groupselection").change(function(){
		var selectedGroupname = $("#groupselection").val();
		if (selectedGroupname != "")
		{
			if(CheckIsUserMemberOfGroup(selectedGroupname) == true)
			{ $("#debugbox").append('User ISMEMBER of group ' + selectedGroupname+'<br/>');
			} else {$("#debugbox").append('User is not member of group ' + selectedGroupname+'<br/>');}
		}
		else
			$("#debugbox").append('Group selection Empty');	
	});
});

function CheckIsUserMemberOfGroup(grouptocheck)
{
	var result = false;
	var selector = 'Group[Name=\'' + grouptocheck + '\']';
	$().SPServices({
		operation: "GetGroupCollectionFromUser",
		userLoginName: $().SPServices.SPGetCurrentUser(),
		async: false,
		completefunc: function(xData, Status) {
			if($(xData.responseXML).find(selector).length == 1) {
				result = true;
        }
      }
   });
   return result;
}
</script>

Open in new window

I filled the select options with SharePoint groups of my current site. Each time I change the option, another test is made.
HTH
Rainer
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
OneNote and SharePoint 10 62
Set Default Values in SharePoint List Edit View using JavaScript 5 60
sharepoint list help 2 28
Sharepoint User Name Displaying incorrectly. 17 41
Work Over Net is a new and very powerful collaboration product. With its new easy interface it is becoming very competitive to other similar products like webex and office interactive. WON 2010 have the standard business tools needed for multi-offic…
We had a requirement to extract data from a SharePoint 2010 Customer List into a CSV file and then place the CSV file into a directory on the network so that the file could be consumed by an AS400 system. I will share in Part 1 how to Extract the Da…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question