Saturday, 25 May 2013

Sharepoint 2013 - Add SP User to a SP Group using CSOM - javascript

In many scenarios we want to add a SP user to a group in Sharepoint.

Since, in SP 2013 client object model is very rich we can very much do all the stuff using CSOM.

Here, i m describing a use case to add a SP User to a SP Group using javascript.

Below is the javascript code:

var user;
var visitorsGroup;

function AddUsers()
{
//Load Current Site
var clientContext = new SP.ClientContext();

//Get all groups in site
var groupCollection = clientContext.get_web().get_siteGroups();
      
// Get the group by name
visitorsGroup = groupCollection.getByName('Approvers');
      
//ensure SP User
var usr2 = clientContext.get_web().ensureUser('domain\\loginname');
      
//Get all SP Users in SP Group
var userCollection = visitorsGroup.get_users();
      
//Add User to Group
var oUSR2 = userCollection.addUser(usr2);

//Load data
clientContext.load(oUSR2); clientContext.load(userCollection);  
      
//Execute Query
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); 
        }

        function onQuerySucceeded() {
            alert("Done");
        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }