1

I'm writing a script that adds user to a group (for example readers) on a site using a form and a PeoplePicker field. But I also want the script to be able to handle not only users, but also if it is a SP-group.

This is what I have so far:

var addUsersToRole = function (clientContext, web, roleType, userNameArray) {
    var deferred = $.Deferred();
    var roleAssignments = web.get_roleAssignments();
    var roleDefinitions = web.get_roleDefinitions();
    var binding = SP.RoleDefinitionBindingCollection.newObject(clientContext);
    var role = roleDefinitions.getByType(roleType);
    binding.add(role);
    $.each(userNameArray, function (index, userName) {
        var user = web.ensureUser(userName);
        roleAssignments.add(user, binding);
    });

    var onSuccess = function (data) {
        deferred.resolve();
    };
    var onFailure = function (data) {
        deferred.reject("Could not add users to role");
    };

    clientContext.executeQueryAsync(onSuccess, onFailure);
    return deferred;
};

Now I'm using var user = web.ensureUser(userName); to get my user, but this doesn't work if the it's not a user, but rather a group. I could easily get weather the item is in fact a user or a group, but I don't know how to add it to the role. I need something like web.ensureGroup(groupName).

Edit: I'm talking about SharePoint-group, not AD-groups

  • I tried your code and it works fine also for AD groups. Did you mean AD group or SharePoint group? – MdMazzotti Mar 14 '14 at 16:12
  • FYI (And I'm not sure if this relates to your case) you cannot add Sharepoing groups to other SharePoint groups. Only users or Active Directory groups can be added to SharePoint groups. – Kolten Mar 14 '14 at 22:08
  • Sorry I wasn't clear enough, I meant SharePointgroup – stinaq Mar 17 '14 at 8:18
1

Have you tried just getting the Group object and passing that in the roleAssignments.Add call in place of the user object? Something like this:

var memberGroup = web.get_siteGroups().getByName("Members");
roleAssignments.add(memberGrooup, binding);

I know I've done this but don't recall exactly how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.