How to check if a user group with a particular is already present in sharepoint using javascript or JSOM? and if not present then create one.. I am new to sharepoint and got info everywhere with C# code
-
1Are you asking if current user is a part of particular group OR you want to list out all groups within Site? and then see if a particular group exists?– DvGCommented Jun 29, 2017 at 6:52
-
I want to list out all groups and check if the particular group with a given name exists or not– zainulCommented Jun 29, 2017 at 6:54
-
Please share your support by marking as answer and up-voting; If It solved your purpose.– DvGCommented Jun 29, 2017 at 8:00
Add a comment
|
1 Answer
Below is the complete code which meets your requirement.
- Check if particular SP group Exist
- If not, Create one
<script language="javascript" type="text/javascript">
function clickMe() {
var clientContext = new SP.ClientContext.get_current();
siteGroups = clientContext.get_web().get_siteGroups();
clientContext.load(siteGroups);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
function onQuerySucceeded() {
var ifGroupExist = false;
for (var i =0 ; i < siteGroups.get_count(); i++)
{
if("my_particular_group_name" == siteGroups.itemAt(i).get_title()){
ifGroupExist = true;
}
}
// create SP group if it does not exist
if(!ifGroupExist) { createSPGroup();}
}
function onQueryFailed() {
alert('Request failed');
}
function createSPGroup()
{
var web = context.get_web();
var groupCollection = web.get_siteGroups();
// Create Group information for Group
var newGRP = new SP.GroupCreationInformation();
newGRP.set_title("your_particular_Group");
newGRP.set_description("sample description");
var currentUser = web.get_currentUser();
context.load(currentUser);
context.load(web, 'Title', 'HasUniqueRoleAssignments');
context.executeQueryAsync(function() {
if (!web.get_hasUniqueRoleAssignments()) {
web.breakRoleInheritance(true, false);
}
//add group to site gorup collection
var newCreateGroup = groupCollection.add(newGRP);
//Role Definition
var rolDef = web.get_roleDefinitions().getByName("Edit");
var rolDefColl = SP.RoleDefinitionBindingCollection.newObject(context);
rolDefColl.add(rolDef);
// Get the RoleAssignmentCollection for the target web.
var roleAssignments = web.get_roleAssignments();
// assign the group to the new RoleDefinitionBindingCollection.
roleAssignments.add(newCreateGroup, rolDefColl);
//Set group properties
newCreateGroup.set_allowMembersEditMembership(true);
newCreateGroup.set_onlyAllowMembersViewMembership(false);
newCreateGroup.update();
context.load(newCreateGroup);
context.executeQueryAsync(success, fail);
}
function success() {
alert("Successfully created group: your_particular_Group");
}
function fail() {
alert("Failed to create group");
}
</script>