I want to add users to a public group based on profile. This is what i have done so far.
trigger newUserTrigger on User (after insert) {
string name = 'test Apex trigger';
list<groupMember> groupList = new list<groupMember>();
list<Group> grp = [select id from Group where name = : name];
for(User us : trigger.new){
if((us.profile.name == 'standard user') || (us.profile.name == 'standard platform user')){
for(group g : grp){
groupMember gp = new groupMember(groupId = g.Id);
gp.UserOrGroupId = us.Id;
groupList.add(gp);
}
}
}
if(groupList.size() > 0)
insert groupList;
}
I am not getting any error but the user is not getting added to the group.
Updated code
trigger newUserTrigger on User (after insert, after update) {
string name = 'test_Apex_trigger';
list<groupMember> groupList = new list<groupMember>();
list<Group> grp = [select id from Group where name = : name];
for(User us : trigger.new){
System.debug('before if '+us.name);
if(us.profile.name.equalsIgnoreCase('Standard User') || us.profile.name.equalsIgnoreCase('Standard Platform User')){
system.debug('after if '+us.name);
for(group g : grp){
groupMember gp = new groupMember(groupId = g.Id);
gp.UserOrGroupId = us.Id;
groupList.add(gp);
}
}
}
if(groupList.size() > 0)
insert groupList;
}
There are no users in the user object