Client Object Model to Determine Whether a User Belongs to a Group and Hide Controls in New/Edit Forms

Introduction

In Share Point we have if conditions such as "If this user is a member of this share point group". We can use this condition to determine whether or not a user belongs to a specific group.

Cause

Determine whether a user belongs to a SharePoint Group and hide some controls in new or edit forms in a SharePoint Custom List.

Approver option

Solution

The following script will help you determine whether the current logged in SharePoint user belongs to a SharePoint user group and based on it hide some controls in a new or edit form in a Custom List.

Step 1

Navigate to your SharePoint 2013 site.

Step 2

From this page select Site Actions | Edit Page.

Edit the page, go to the "Insert" tab in the Ribbon and click the "Web Part" option. In the "Web Parts" picker area, go to the "Media and Content" category, select the "Script Editor" Web Part and press the "Add button".

Step 3

Once the Web Part is inserted into the page, you will see an "EDIT SNIPPET" link; click it. You can insert the HTML and/or JavaScript as in the following:

Script

  1. <script src="/sites/JS/jquery-1.4.2.min.js"></script><script type="text/javascript">  
  2.    
  3.    
  4. ExecuteOrDelayUntilScriptLoaded(disableControls, "sp.js");  
  5.    
  6. var clientContext = null;  
  7.         var web = null;  
  8.         var users ;  
  9.         var oList;  
  10.         var oListNew;  
  11.    
  12. function disableControls()  
  13. {  
  14. clientContext = new SP.ClientContext();  
  15. var groupCollection = clientContext.get_web().get_siteGroups();  
  16. var group = groupCollection.getById(4);//the SharePoint usergroup  
  17. users = group.get_users();  
  18. clientContext.load(group);  
  19. clientContext.load(users);  
  20. currentUser = clientContext.get_web().get_currentUser();  
  21. clientContext.load(currentUser);  
  22. clientContext.executeQueryAsync(Function.createDelegate(this,  
  23. this.onQuerySucceeded), Function.createDelegate(this,  
  24. this.onQueryFailed));  
  25. RefreshCommandUI();  
  26. }  
  27. function onQuerySucceeded()  
  28. {  
  29. if(this.users.get_count() >0)  
  30. {  
  31. var UserExistInGroup = false;  
  32. for(var i=0; i < users.get_count(); i++)  
  33. {  
  34.   
  35. if(users.itemAt(i).get_loginName() == this.currentUser.get_loginName())  
  36. {  
  37. UserExistInGroup = true;  
  38. break;  
  39. }  
  40. }  
  41. }  
  42. if (UserExistInGroup)  
  43. {  
  44. $('nobr:contains("Approver")').closest('tr').show();  
  45. }  
  46. else  
  47. {  
  48.  $('nobr:contains("Approver")').closest('tr').hide();   
  49. }  
  50. }  
  51. function onQueryFailed(sender, args)  
  52. {  
  53.    
  54. }  
  55. </script>  
Final Result

add new item