1

I have created one group using csom javascript upto here working fine . I want to how to add users to particular group using csom javascript.Any ideas?

2 Answers 2

2

Straight from MSDN (https://msdn.microsoft.com/en-us/library/office/hh185012(v=office.14).aspx)

var siteUrl = '/sites/MySiteCollection ';

function addUserToSharePointGroup() {
    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    var userCreationInfo = new SP.UserCreationInformation();
    userCreationInfo.set_email('[email protected]');
    userCreationInfo.set_loginName('DOMAIN\alias');
    userCreationInfo.set_title('John');
    this.oUser = oGroup.get_users().add(userCreationInfo);
    clientContext.load(oUser);
    clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {       
    alert(this.oUser.get_title() + " added.");
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n'+args.get_stackTrace());
}
2

Even though Marius's answer is correct, I find this a bit more clean. It takes an array of user names and a group name. Works for any number of users.

function addUsersToGroup (usernames, groupName) {
    //Get the web
    var clientContext = SP.ClientContext.get_current();
    var web = clientContext.get_web();

    //Get the group from the web
    var group = web.get_siteGroups().getByName(groupName);

    for (var i = usernames.length - 1; i >= 0; i--) {
        //Use 'ensureUser()' to get an SP_User object
        group.get_users().addUser(web.ensureUser(usernames[i]));
    };

    group.update();

    //Load the group to the client context and execute
    clientContext.load(group);
    clientContext.executeQueryAsync(onSuccess, onFail);
}

And call it with

var users = ["Peter Griffin", "Stewie Griffin"];
var group = "Family guy cast";

addUsersToGroup(users, group);
2
  • 1
    The function is incomplete, you forget to get the correct group (groupName parameter is unused). Also, you're trying to add the user to the an SPGroupCollection. var group = web.get_siteGroups().getByName(groupName); Commented Oct 6, 2015 at 11:52
  • True! I erased a bit too much when I copied it from my source! Thanks! Commented Oct 6, 2015 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.