Everything (ideal scenario) in SharePoint is now an App. SharePoint hosted Apps uses JavaScript Object Model (JSOM).So now developers have to code more on JavaScript and learn more about doing even administrative tasks using JavaScript. In this blog i will detail one such administration task- Changing the permission of any SharePoint group. Below is a sample code to change the group’s permission:
function ChangePermissions(groupMembershipID,permissionLevel) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
//Get Role Definition by name
var roleDef = web.get_roleDefinitions().getByName(permissionLevel);
var roleDefBinding = SP.RoleDefinitionBindingCollection.newObject(clientContext);
// Add the role to the role definiiton binding.
roleDefBinding.add(roleDef);
// Get the RoleAssignmentCollection for the web.
var assignments = web.get_roleAssignments();
//Get the role assignment for the group using Group 's membership id
var groupRoleAssignment = assignments.getByPrincipalId(groupMembershipID);
groupRoleAssignment.importRoleDefinitionBindings(roleDefBinding);
groupRoleAssignment.update();
clientContext.executeQueryAsync(function () {
alert("Permissions changed !");
},
function (sender, args) {
console.log(args.get_message());
});
});
}
Tweaking above code to access Host Web in SharePoint Hosted App
If you are trying this code in a SharePoint hosted App and needs to change the permission of group in the host web , just change the way you generate the ClientContext and web object as below.
var clientcontext = SP.ClientContext.get_current();
var hostUrl = GetUrlKeyValue("SPHostUrl");
var hostContext = new SP.AppContextSite(clientContext, hostUrl);
var web = hostContext.get_web();
Leave a Reply