function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Piyush Tawari 9Piyush Tawari 9 

Trigger on User to update group membership of user based on user profile and custom setting

My question is to Create a trigger on User to update group membership of user based on user profile and custom setting. Create  Custom settings which will store the mapping of the groups to Profiles.On Insert/Update of  User, trigger will recalculate the group membership of the user based on the mapping stored in custom settings. i Have done for insert part but for Update there are too many possibilities that can happen. So please if anyone knows answer help me.
trigger GroupMembership on User (after update,after insert) {

    list<custom_setting__c> setting = custom_setting__c.getAll().values();
    list <GroupMember> GrpMem = new list<groupMember>();
    list<GroupMember> Grp = [select id,UserOrGroupId,GroupId from GroupMember];
   
    for(User usr : trigger.new)
    { 
        if(trigger.isInsert)
        {
            for(Custom_setting__c custom : setting)
            {    Id cusId = (Id)custom.Profile_Id__c;
                if(cusId == usr.ProfileId)
                {
                    GroupMember GM = new GroupMember();
                    GM.GroupId = (Id)custom.Group_id__c;
                    GM.UserOrGroupId = usr.Id;
                    GrpMem.add(GM);
                }
            }
       
        } 
    } 
insert GrpMem;
}
This is my code when adding new user. Help me with Update code.
Best Answer chosen by Piyush Tawari 9
Rohit B ☁Rohit B ☁
Hi Piyush,
In update why don't you simply delete the records the first and then call your insert method?

 Move this code to new function and call it for insertion into GroupMember.
list <GroupMember> GrpMem = new list<groupMember>();
​for(User usr : trigger.new)
    { 
        if(trigger.isInsert)
        {
            for(Custom_setting__c custom : setting)
            {    Id cusId = (Id)custom.Profile_Id__c;
                if(cusId == usr.ProfileId)
                {
                    GroupMember GM = new GroupMember();
                    GM.GroupId = (Id)custom.Group_id__c;
                    GM.UserOrGroupId = usr.Id;
                    GrpMem.add(GM);
                }
            }
       
        } 
    } 
insert GrpMem;
}

In update just gather all the users and query like this 
 
list<GroupMember> ExistingUsers = [select id,UserOrGroupId,GroupId from GroupMember WHERE UserOrGroupId in :lstUsers];
and delete these Existing Users and then call ur insert function.
[NOTE : I'm assuming one user per group]

Hope it helps.. :)

All Answers

Rohit B ☁Rohit B ☁
Hi Piyush,
In update why don't you simply delete the records the first and then call your insert method?

 Move this code to new function and call it for insertion into GroupMember.
list <GroupMember> GrpMem = new list<groupMember>();
​for(User usr : trigger.new)
    { 
        if(trigger.isInsert)
        {
            for(Custom_setting__c custom : setting)
            {    Id cusId = (Id)custom.Profile_Id__c;
                if(cusId == usr.ProfileId)
                {
                    GroupMember GM = new GroupMember();
                    GM.GroupId = (Id)custom.Group_id__c;
                    GM.UserOrGroupId = usr.Id;
                    GrpMem.add(GM);
                }
            }
       
        } 
    } 
insert GrpMem;
}

In update just gather all the users and query like this 
 
list<GroupMember> ExistingUsers = [select id,UserOrGroupId,GroupId from GroupMember WHERE UserOrGroupId in :lstUsers];
and delete these Existing Users and then call ur insert function.
[NOTE : I'm assuming one user per group]

Hope it helps.. :)
This was selected as the best answer
rajat Maheshwari 6rajat Maheshwari 6

Hi Piyush,

Please find below code snippet and let me know in cas eof any help :)

 

trigger GroupMembership on User (after update,after insert) {




    list<custom_setting__c> setting = custom_setting__c.getAll().values();
Map<String,custom_setting__c> mp_CustomSetting = new Map<String,custom_setting__c>();
Map<Id,GroupMember> mp_GroupMember = new Map<Id,GroupMember>
List<GroupMember> GrpMem = new List<GroupMember>();
set<Id> set_GroupId = new set<Id>();

for(custom_setting__c customRecord : setting)
  {
    mp_CustomSetting.put(customRecord.Profile_Id__c,customRecord);
  }

if(Trigger.isAfter && Trigger.isInsert)
 {
    for(User usr : trigger.new)
    { 
       if(mp_CustomSetting!=null && mp_CustomSetting,containsKey(usr.ProfileId))
           {
            
                    GroupMember GM = new GroupMember();
                    GM.GroupId =mp_CustomSetting.get(usr.ProfileId).Group_id__c;
                    GM.UserOrGroupId = usr.Id;
                    GrpMem.add(GM);
                }
            }
       
        } 

if(Trigger.isAfter && Trigger.isUpdate)
  {
      for(User usr : trigger.new)
      { 
	     if(mp_CustomSetting!=null && mp_CustomSetting.containsKey(usr.ProfileId))
             set_GroupId.add(mp_CustomSetting.get(usr.ProfileId).Group_id__c);
      }
	  
    for(GroupMember GM : [Select Id,GroupId,UserOrGroupId from GroupMember where GroupId IN:set_GroupId])
	  {
	     mp_GroupMember.put(GM.GroupId,GM);
	  }
	  
	  for(User usr : trigger.new)
      { 
	     if(mp_GroupMember!=null && mp_CustomSetting!=null && mp_CustomSetting.containsKey(usr.ProfileId) && mp_GroupMember.containsKey(mp_CustomSetting.get(usr.ProfileId).Group_id__c))
             mp_GroupMember.get(mp_CustomSetting.get(usr.ProfileId).Group_id__c).UserOrGroupId = usr.Id;
      }


    } 
	
	
	
	if(GrpMem!=null && GrpMem.size()>0)
	   insert GrpMem;
	   
	if(mp_GroupMember!=null && mp_GroupMember.value()!=null)
	    update mp_GroupMember.value();

}

Thanks
Rajat Maheshwari
rajatzmaheshwari@gmail.com
Piyush Tawari 9Piyush Tawari 9
Hi Rohit,
If user's old and new both profile belong to same group then he should remain in that group. But in your solution we are deleting him from that group and again adding him. So its not really Updating his membership of Group? Can we do it without deleting it?
Piyush Tawari 9Piyush Tawari 9
Hi Rajat Maheshwari ,
You are considering that one profile is associated with one group only right?
rajat Maheshwari 6rajat Maheshwari 6

Piyush,

Yes , You are right, I am considering one profile associated with one group

Please let me know, the same.

Thanks

Piyush Tawari 9Piyush Tawari 9
Hi Rajat,
What can we do if one profile is associated with more than one group? I tried using loops but ended up with 3 - 4 for loops in each other.
rajat Maheshwari 6rajat Maheshwari 6

Piyush, first let me know, for insert operation, This code works for you, afterwards I will switch to update operation


trigger GroupMembership on User (after update,after insert) {




    list<custom_setting__c> setting = custom_setting__c.getAll().values();
Map<String,List<custom_setting__c>> mp_CustomSetting = new Map<String,List<custom_setting__c>>();
Map<Id,GroupMember> mp_GroupMember = new Map<Id,GroupMember>
List<GroupMember> GrpMem = new List<GroupMember>();
set<Id> set_GroupId = new set<Id>();

for(custom_setting__c customRecord : setting)
  {

  if(mp_CustomSetting!=null && mp_CustomSetting.containsKey(customRecord.Profile_Id__c)
    {
        List<custom_setting__c> lst_Custom = mp_CustomSetting.get(customRecord.Profile_Id__c);

lst_Custom.add(customRecord);
mp_CustomSetting.put(customRecord.Profile_Id__c, lst_Custom);

}
else
 {
    mp_CustomSetting.put(customRecord.Profile_Id__c, new List<custom_setting__c>{customRecord};
}

}

  

if(Trigger.isAfter && Trigger.isInsert)
 {
    for(User usr : trigger.new)
    { 
       if(mp_CustomSetting!=null && mp_CustomSetting,containsKey(usr.ProfileId))
           {
               List<custom_setting__c> list_Custom = mp_CustomSetting.get(usr.profileId);

                   for(custom_setting__c CS : list_Custom)
                      {
                    GroupMember GM = new GroupMember();
                    GM.GroupId =CS .Group_id__c;
                    GM.UserOrGroupId = usr.Id;
                    GrpMem.add(GM);
                       }
                }
            }
       
        } 



    
	
	
	
	if(GrpMem!=null && GrpMem.size()>0)
	   insert GrpMem;
	   
	

}

Thanks
Rohit B ☁Rohit B ☁
Hi Piyush,
Although it simpify the execution of operation that's y I suggested that approach but if you don't want to delete the user from the group if group are same then u just need to perform some comparisons with the groups.
If you want me to write the code then tell me. I'll be happy to help you.
 
Piyush Tawari 9Piyush Tawari 9
Hi Rohit ,
I would love if you can write that code for me because when I am writing that code I am ending up with 3-4 inner loops.
rajat Maheshwari 6rajat Maheshwari 6
Hi Piyush,

Did you get a chance to look over my code ?

Please let me know in case of any query/help. I am happy to help you :)

Thanks
Rajat Maheshwari
rajatzmaheshwari@gmail.com