3

I would like to automatically add and remove user from a public group.

When they got assigned to a specific profile, they should be added to this group and when the profile has been changed to anything else, they should get moved away from the group.

I made myself a code but due to the fact, that in groupmembers, the profileid is not supported, i am kinda lost here. And in the group are always more then 1 person, and only one specific person should be removed.

is it possible to get the id of the user which caused the trigger to run?

Maybe you could help me?

here is the trigger so far:

trigger AddToPublicGroup on User (after insert, after update) {    List<GroupMember> GMlist = new List<GroupMember>();
for (User a : trigger.new){
    if (a.profileid != '00eD0000001QPRa') {
        GroupMember GL  = [Select Id from GroupMember where GroupId = '00GL0000001AMGt'];
        delete GL;
        }
else
            if (a.profileid == '00eD0000001QPRa') {
     GroupMember GM = new GroupMember();
            GM.GroupId = '00GL0000001AMGt';
            GM.UserOrGroupId = a.Id;
            GMList.add(GM) ;
            insert GMList;        
}}
}

1 Answer 1

1

Ralf,

you can use the same field UserOrGroupId that you have used in the insert part to identify the group member by user id and then delete it.

here's a modified version - I have moved the SOQL & DML statements out of the for loop so it covers trigger bulkification as well..

trigger AddToPublicGroup on User (after insert, after update) {    
    Id groupId = '00GL0000001AMGt';
    Id profileId = '00eD0000001QPRa';
    List<GroupMember> GMlist = new List<GroupMember>();
    Set<Id> userIdSet = new Set<Id>();
    for (User a : trigger.new){
        if (a.profileid != profileId) {
            userIdSet.add(a.Id);
        }
        else if (a.profileid == profileId) {
            GroupMember GM = new GroupMember();
            GM.GroupId = groupId;
            GM.UserOrGroupId = a.Id;
            GMList.add(GM) ;
      }         }

     List<GroupMember> grpList  = [Select Id from GroupMember where GroupId =: groupId and UserOrGroupId in : userIdSet ];

     delete grpList;

     if(GMList.size() > 0) insert GMList;
}
3
  • Thx a lot! works great! just one thing, u missed ">" here "Set<ID.()" Commented May 29, 2015 at 13:35
  • updated the set statement. Commented May 29, 2015 at 13:36
  • me too updated ;) Commented May 29, 2015 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .