Skip to content

Instantly share code, notes, and snippets.

@karanrajs
Last active August 29, 2015 14:05
Show Gist options
  • Save karanrajs/f4ad8ac19d3250342c8b to your computer and use it in GitHub Desktop.
Save karanrajs/f4ad8ac19d3250342c8b to your computer and use it in GitHub Desktop.
Batch class to remove user from group, if the user is assigned to multiple group
global class userGroupRemoval implements Database.Batchable<sObject> {
String query = 'Select Id from user where isActive = true';
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope) {
List<user> userRecord = (List<user>)scope;
List<GroupMember> duplicateGroupId = new List<GroupMember>();
Set<Id> userId = new Set<Id>();
for(GroupMember gpm : [Select Id,userorGroupId from GroupMember where userorGroupId IN:userRecord]){
if(userId.contains(gpm.userorGroupId)){
duplicateGroupId.add(gpm);
}
userId.add(gpm.userorGroupId);
}
if(duplicateGroupId.size() > 0)
delete duplicateGroupId;
}
global void finish(Database.BatchableContext BC) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment