Steps for Implementation
- Get Current Context.
- Get App web URL and Host Web URL from Query string parameter.
- Calling CreateMultipleGroup method in document ready.
- Get web from app context site.
- Create new group Information
- Get Role definition by name (permission for the Group)
- Add group and add the role to the collection.
- Set Allow membership then set Group Owner
- Push oMembersGRP in array
- Then load the array
- Finally execute
In your JavaScript file write the following code,
-
- 'use strict';
-
- var context = SP.ClientContext.get_current();
-
- varhostWebURL, appWebURL;
-
- $(document).ready(function () {
-
- hostWebURL = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
- appWebURL = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
-
- CreateMultipleGroup ();
- });
- function CreateMultipleGroup()
- {
- var permission = ["TestGroup", "TestGroup1", "TestGroup2"];
- var membershipArray = [];
- var deferred = $.Deferred();
-
- var currentWEB = context.get_web();
-
- var membersGRP = new SP.GroupCreationInformation();
-
- var rdContribute = currentWEB.get_roleDefinitions().getByName("Contribute");
- for (var i = 0; i < permission.length; i++)
- {
- var collContribute = SP.RoleDefinitionBindingCollection.newObject(context);
- membersGRP.set_title(permission[i]);
- membersGRP.set_description('Use this group to grant people contribute permissions to the SharePoint site:');
-
- var oMembersGRP = currentWEB.get_siteGroups().add(membersGRP);
-
- collContribute.add(rdContribute);
-
- oMembersGRP.set_allowMembersEditMembership(false);
-
- var groupOwner = currentWEB.get_siteGroups().getByName("GroupName");
- oMembersGRP.set_owner(groupOwner);
- oMembersGRP.set_onlyAllowMembersViewMembership(false);
- oMembersGRP.update();
-
- membershipArray.push(oMembersGRP);
- context.load(membershipArray[membershipArray.length - 1]);
- }
-
- context.executeQueryAsync(
- function () {
- deferred.resolve();
- alert("Group Created Successfully");
- },
- function (sender, args) {
- deferred.reject();
- alert("Failed to create groups " + args.get_message());
- });
- return deferred.promise();
- }
-
- function manageQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- var strParams = "";
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) {
- return singleParam[1];
- }
- }
- }
Summary
In this blog we have explored how to create multiple SP user group in single Asynchronous process using JSOM. If we follow the single asynchronous process for creating multiple groups the performance will improve. Happy Coding!