Monday, 27 May 2013

Sharepoint 2013 - Create a SP Group using CSOM javascript

In this example we will get to know how to create and assign permission to a SP Group using CSOM - client object model in javascript.

//Sample - http://msdn.microsoft.com/en-us/library/jj246414.aspx
function createSPGroups()
{
//Load new Site
   var currentCTX = new SP.ClientContext();
   var currentWEB  = currentCTX.get_web();

   //Get all groups in site
   var groupCollection = currentWEB.get_siteGroups();

   // Create Group information for Group
var membersGRP = new SP.GroupCreationInformation();
membersGRP.set_title('Group Name');
membersGRP.set_description('Use this group to grant people contribute permissions to the SharePoint site: ');


//add group
oMembersGRP = currentWEB.get_siteGroups().add(membersGRP);

//Get Role Definition by name (http://msdn.microsoft.com/en-us/library/jj246687.aspx)
//return SP.RoleDefinition object
var rdContribute = currentWEB.get_roleDefinitions().getByName('Contribute');

// Create a new RoleDefinitionBindingCollection.
        var collContribute = SP.RoleDefinitionBindingCollection.newObject(currentCTX);
     
        // Add the role to the collection.
        collContribute.add(rdContribute);

// Get the RoleAssignmentCollection for the target web.
        var assignments = currentWEB.get_roleAssignments();
     
 // assign the group to the new RoleDefinitionBindingCollection.
var roleAssignmentContribute = assignments.add(oMembersGRP, collContribute);

currentCTX.load(oMembersGRP);

//Execute Query
currentCTX.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());
        }

Here, I my assigning a predefined permission level i.e. Contribute to the group.We can create our own custom permission level and assign to the group.Creating custom permission level will be discussed in upcoming blogs.