Managing SharePoint Site User Memberships in Multiple Groups Using SPServices

 

I got an email the other day from Geoff Oliver. He said he had done something pretty useful with SPServices and wondered if I would be interested in seeing it.

I manage about 115 groups in a single site collection…and that number is expected to grow. I found that when a new user came on board or changed duty positions, getting them into the right SP groups was slow and cumbersome through the SP interface.

Using the SPServices libraries, I was able to create a simple interface to add/remove a single user to/from multiple groups at once. When you identify/select a user, it will show you two select lists. The right side will list all of the groups the current user is a member of while the left box shows all the groups the user is NOT a member of. Between the two select lists are buttons to ‘move’ the groups from one side to the other for the identified user (while modifying their memberships appropriately in the process). The select boxes are configured to allow multiple select so you can usually perform the maintenance in just a couple clicks. The code fits neatly into a CEWP.

Of course I wanted to see it. Geoff’s code sounded exactly like the kind of thing that I think SPServices is good for: a useful solution that solves a business problem better than SharePoint out of the box without needing to deploy anything to the server.

Geoff describes himself as:

…a Civilian Project Manager for the Air Force, developing a SharePoint site to assist a large organization with information management and integration with Microsoft Office (sharing/synchronizing data between SharePoint sites and Word/Excel/Access files). I’ve been doing MS Office automation (using VBA) for about 15 years now and SharePoint site development for 7.

The code uses a number of Users and Groups Web Service operations that are wrapped in SPServices:

  • GetUserCollectionFromSite
  • GetGroupCollectionFromUser
  • GetGroupCollectionFromSite
  • AddUserToGroup
  • RemoveUserFromGroup

Here’s Geoff’s code. It’s amazingly compact and gets the job done well.

$(document).ready(function() {
  //Populate the users pick list
  var strHTMLSiteUsers = "";
  $().SPServices({
      operation: "GetUserCollectionFromSite",
      async: false,
      completefunc: function(xData, Status) {
        $(xData.responseXML).find("[nodeName='User']").each(function() {
          strHTMLSiteUsers += "<option value='" + $(this).attr("LoginName") + "'>" + $(this).attr("Name") + "</option>";
        });
        $("#my_SiteUsers").append(strHTMLSiteUsers);
      }
  });
  RefreshGroupLists();
});

function RefreshGroupLists(){
  var strHTMLAvailable = "";
  var strHTMLAssigned = "";
  var arrOptionsAssigned = new Array();
  var intOpts = 0;
  var booMatch;
  var booErr = "false";

  $("#my_SPGroupsAssigned").html("");
  $("#my_SPGroupsAvailable").html("");

  if($("#my_SiteUsers").attr("value") == 0){
    alert("You must select a user");
    return;
  }

  //Populate the Groups Assigned
  $().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: $("#my_SiteUsers").attr("value"),
      async: false,
      completefunc: function(xData, Status) {
        $(xData.responseXML).find("[nodeName='errorstring']").each(function() {
          alert("User not found");
          booErr = "true";
          return;
        });
        $(xData.responseXML).find("[nodeName='Group']").each(function() {
          strHTMLAvailable += "<option value='" + $(this).attr("Name") + "'>" + $(this).attr("Name") + "</option>";
          arrOptionsAssigned[intOpts] = $(this).attr("Name");
          intOpts = intOpts + 1;
        });
        $("#my_SPGroupsAssigned").append(strHTMLAvailable);
      }
  });

  //Populate available site groups
  if(booErr == "false"){
    $().SPServices({
        operation: "GetGroupCollectionFromSite",
        async: false,
        completefunc: function(xData, Status) {
          $(xData.responseXML).find("[nodeName='Group']").each(function() {
            booMatch = "false";
            for (var i=0;i<=arrOptionsAssigned.length;i++){
              if($(this).attr("Name") == arrOptionsAssigned[i]){
                booMatch = "true";
                break;
              }
            }
            if(booMatch == "false"){
              strHTMLAssigned += "<option value='" + $(this).attr("Name") + "'>" + $(this).attr("Name") + "</option>";
            }
          });
          $("#my_SPGroupsAvailable").append(strHTMLAssigned);
        }
    });
  }
}

function AddGroupsToUser(){
  var i;

  if($("#my_SiteUsers").attr("value") == 0){
    alert("You must select a user");
    return;
  }

  if($("#my_SPGroupsAvailable").val() == null){
    alert("You haven't selected any groups to add");
    return;
  }
  else{
    var arrGroups = $("#my_SPGroupsAvailable").val();
    for (i=0;i<arrGroups.length;i++){
      $().SPServices({
          operation: "AddUserToGroup",
          groupName: arrGroups[i],
          userLoginName: $("#my_SiteUsers").attr("value"),
          async: false,
          completefunc: null
      });
    }
    RefreshGroupLists();
  }
}

function RemoveGroupsFromUser(){
  var i

  if($("#my_SiteUsers").attr("value") == 0){
    alert("You must select a user");
    return;
  }

  if($("#my_SPGroupsAssigned").val() == null){
    alert("You haven't selected any groups to remove");
    return;
  }
  else{
    var arrGroups = $("#my_SPGroupsAssigned").val();
    for (i=0;i<arrGroups.length;i++){
      $().SPServices({
          operation: "RemoveUserFromGroup",
          groupName: arrGroups[i],
          userLoginName: $("#my_SiteUsers").attr("value"),
          async: false,
          completefunc: null
      });
    }
    RefreshGroupLists();
  }
}

and the associated markup:

<table align="center">
  <tr>
    <td colspan="3" style="text-align:center">
      <font style="font-weight:bold">Select a User:   </font>
      <select id="my_SiteUsers" style="width:350px;" onchange="RefreshGroupLists()"></select>
    </td>
  </tr>
  <tr>
    <th class='ms-vh2'>Available Groups</th>
    <th></th>
    <th class='ms-vh2'>Assigned Groups</th>
  </tr>
  <tr>
    <td class='ms-vb2'>
      <select id="my_SPGroupsAvailable" style="width:250px;height:450px;" multiple="multiple"></select>
    </td>
    <td>
      <button id="my_AddGroupsToUser" style="width:80px;" onclick="AddGroupsToUser()">>></button><br><br>
      <button id="my_RemoveGroupsFromUser" style="width:80px;" onclick="RemoveGroupsFromUser()"><<</button></td>
    <td class='ms-vb2'>
      <select id="my_SPGroupsAssigned" style="width:250px;height:450px;" multiple="multiple"></select>
    </td>
  </tr>
</table>

And here’s the net result. It’s a simple little form that does exactly what Geoff said it would. All I had to do to get it running in my environment was to change the references to the script files to point where I have them stored. Otherwise, it worked with no modification whatsoever.

2011-11-06-ManagingSPUserMembership-01.png

This is the sort of thing that may belong in SPServices. Of course, you can simply copy and use the code above, but perhaps some more options and additional functionality would make it even more useful. What do you think? Is this something you’d use?

And thanks for sharing, Geoff.