In this blog I would like to explain share the code for create a user group in SP host web using JavaScript Object Model.
  1. //get Current Context
  2. var context = SP.ClientContext.get_current();
  3. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  4. $(document).ready(function () {
  5. console.log("page loading...")
  6. $("#btnCreate").click(function () {
  7. CreateSharePointGroup();
  8. });
  9. });
  10. //this method is used to create a group
  11. function CreateSharePointGroup() {
  12. //Get host web URL here
  13. var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
  14. var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
  15. var currentWEB = appCtxSite.get_web();
  16. // Create Group information for Group
  17. var membersGRP = new SP.GroupCreationInformation();
  18. membersGRP.set_title("GroupName");
  19. membersGRP.set_description('Use this group to grant people full control permissions to the SharePoint site: ');
  20. //add group
  21. var oMembersGRP = currentWEB.get_siteGroups().add(membersGRP);
  22. //return SP.RoleDefinition object
  23. var rdContribute = currentWEB.get_roleDefinitions().getByName("Full Control");
  24. // Create a new RoleDefinitionBindingCollection.
  25. var collContribute = SP.RoleDefinitionBindingCollection.newObject(context);
  26. // Add the role to the collection.
  27. collContribute.add(rdContribute);
  28. // Get the RoleAssignmentCollection for the target web.
  29. var assignments = currentWEB.get_roleAssignments();
  30. // assign the group to the new RoleDefinitionBindingCollection.
  31. var roleAssignmentContribute = assignments.add(oMembersGRP, collContribute);
  32. context.load(oMembersGRP);
  33. context.executeQueryAsync(function () {
  34. alert("Sharepoint Group is created Successfully..")
  35. }, function (sender, args) {
  36. onfail(sender, args);
  37. });
  38. }
  39. // This function is executed if the above call fails
  40. function onfail(sender, args) {
  41. alert('Failed to create group. Error:' + args.get_message());
  42. }
  43. // this method used split the query string
  44. function manageQueryStringParameter(paramToRetrieve) {
  45. var params = document.URL.split("?")[1].split("&");
  46. var strParams = "";
  47. for (var i = 0; i < params.length; i = i + 1) {
  48. var singleParam = params[i].split("=");
  49. if (singleParam[0] == paramToRetrieve) {
  50. return singleParam[1];
  51. }
  52. }
  53. }
In app manifest file provide full control permission to the site collection as shown in below,
Summary
In this article we have explored how to create a user group in SharePoint host web using JavaScript object model.