Use Case:

NOTE: An extended version of Example 8

(Example 8: Whenever a new User having profile “System Administrator” is inserted and is Active, add the user to the public group “Admins”.

Pre-requisite: Create a public group with name as “Admins”.)

Write a trigger: to add the user to the public group “Admins”

    1. If the active user’s profile is updated from anything to System Administrator, the user should be added in the group.
    2. If the active user’s  profile is updated from System Administrator to something else, the user should be removed from the group.
    3. If the user having System Administrator profile is marked active, should be added to the group.
    4. If the user having System Administrator profile is marked inactive, should be removed from the group.
trigger UserTrigger on User (after insert, after update) {
if(Trigger.isAfter) {
if(Trigger.isInsert) {
UserTriggerHandler.addAdminToPublicGroup(Trigger.new);
}
if(Trigger.isUpdate) {
UserTriggerHandler.updatePublicGroupUsers(Trigger.new, Trigger.oldMap);
}
}
}


public class UserTriggerHandler {
private static Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];
private static Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
public static void addAdminToPublicGroup(List<User> newUsers) {
// Get Id of Public group for Admins
//Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];
// Perform operation of adding Admin users to the group only when Group is present in salesforce
if(adminGroup != NULL) {
List<GroupMember> groupMembers = new List<GroupMember>();
// Get admin proifle and check for all users,
// if user profile id is same as the admin profile id AND user is active then only create a new group member
//Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
for(User user : newUsers) {
if(user.ProfileId == adminProfile.Id && user.IsActive == true) {
groupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));
}
}
insert groupMembers;
}
}
public static void updatePublicGroupUsers(List<User> newUsers, Map<Id,User> oldUsersMap) {
if(adminGroup != NULL) {
List<GroupMember> newGroupMembers = new List<GroupMember>();
List<GroupMember> existingGroupMembers = [SELECT Id, GroupId, UserOrGroupId FROM GroupMember WHERE Group.Id = :adminGroup.Id];
List<GroupMember> membersToBeDeleted = new List<GroupMember>();
Set<Id> usersAsGroupMembers = new Set<Id>();
for(User user : newUsers) {
// When profile of an active user is changed
if(user.ProfileId != oldUsersMap.get(user.Id).ProfileId && user.IsActive == true) {
// If new profile is System Administrator then create a new group member for admin
if(user.ProfileId == adminProfile.Id) {
newGroupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));
}
// If new profile is Not System Administrator and old profile was System Administrator then delete the existing group member if present
if(oldUsersMap.get(user.Id).ProfileId == adminProfile.Id) {
usersAsGroupMembers.add(user.Id);
}
}
else {
// When user with System Administrator profile is marked active or inactive
if(user.IsActive != oldUsersMap.get(user.Id).IsActive && user.ProfileId == adminProfile.Id) {
// If user is marked active from inactive then create a new group member for admin
if(user.IsActive == true) {
newGroupMembers.add(new GroupMember(GroupId = adminGroup.Id, UserOrGroupId = user.Id));
}
// If user is marked inactive from active, then delete the existing group member if present
if(user.IsActive == false) {
usersAsGroupMembers.add(user.Id);
}
}
}
}
insert newGroupMembers;
for(GroupMember member : existingGroupMembers) {
if(usersAsGroupMembers.contains(member.UserOrGroupId)) {
membersToBeDeleted.add(member);
}
}
delete membersToBeDeleted;
}
}
}

Test Class:

Scenario 1- Verify that when an active user’s profile is changed to System Administrator then GroupMember record is created for the public group Admins.

Scenario 2- Verify that when profile is changed to some profile other than the System Administrator, then GroupMember record is deleted for the public group Admin.

Scenario 3- Verify that when an inactive user with profile System Administrator is made active, then a GroupMember record is created for the public group Admins for the user

Scenario 4- Verify that when an active user with profile System Administrator is made inactive, then a GroupMember record should be deleted for the public group Admins for the user

@isTest
public class TestUserUtil {
public static User createUser(String fName, String lName, String alias, String username, Profile profile) {
User usr = new User(LastName = lName,
FirstName = fName,
Alias = alias,
Email = fName + '.' + lName + '@apexstepbystep.com',
Username = username,
ProfileId = profile.id,
TimeZoneSidKey = 'GMT',
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LocaleSidKey = 'en_US'
);
return usr;
}
}


@isTest
private class UserTriggerTest {
// Verify that when user having System Administrator profile is created, the user is also added to the public group Admin.
@isTest
static void testUserInsertion_valid() {
Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];
// GroupMembers before insertion
List<GroupMember> membersBefore = [SELECT Id From GroupMember Where GroupId = :adminGroup.Id];
Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);
Test.startTest();
insert usr;
Test.stopTest();
// Assert that members after insertion should be exactly 1 greater than before
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'User is not added to group Admins.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be present for the inserted user.');
}
// Verify that when user having other than the System Administrator profile is created, the user should not be added to the public group Admin.
@isTest
static void testUserInsertion_invalid() {
Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];
// GroupMembers before insertion
List<GroupMember> membersBefore = [SELECT Id From GroupMember Where GroupId = :adminGroup.Id];
Profile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', standardProfile);
Test.startTest();
insert usr;
Test.stopTest();
// Assert that members after insertion should be same as before
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size(), membersAfter.size(), 'Group Members count is not same.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember should not be present for the inserted user.');
}
// Verify that when an active user's profile is changed to System Administrator then GroupMember record is created for the public group Admins
@isTest
static void test_updatePublicGroupUsers_profileAdmin() {
        Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];

Profile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', standardProfile);
insert usr;
// GroupMembers in the adminGroup before updation. Assert that user should not be a member of the public group.
List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
Set<Id> groupMembersIdsBefore = new Set<Id>();
for(GroupMember member : membersBefore) {
groupMembersIdsBefore.add(member.UserOrGroupId);
}
System.assertEquals(false, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should not be present for the inserted user.');
// Update profile of the inserted user to System Administrator
Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
Test.startTest();
usr.ProfileId = adminProfile.Id;
update usr;
Test.stopTest();
// Assert that after updating the profile to System Administrator, a new group member for public group Admins should be created
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'Group Members count is same.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be present for the inserted user.');
}
// Verify that when profile is changed to some profile other than the System Administrator, then GroupMember record is deleted for the public group Admin.
@isTest
static void test_updatePublicGroupUsers_profileNotAdmin() {
        Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];

Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);
insert usr;

// GroupMembers in the adminGroup before updation. Assert that user should be a member of the public group.
List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
Set<Id> groupMembersIdsBefore = new Set<Id>();
for(GroupMember member : membersBefore) {
groupMembersIdsBefore.add(member.UserOrGroupId);
}
System.assertEquals(true, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should be present for the inserted user.');
// Update profile of the inserted user to Standard User
Profile standardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
Test.startTest();
usr.ProfileId = standardProfile.Id;
update usr;
Test.stopTest();
// Assert that after updating the profile to Standard User, the group member for public group Admins should be deleted
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size() - 1, membersAfter.size(), 'Group Members count is same.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember is not deleted for the user.');
}
// Verify that when an inactive user with profile System Administrator is made active, then a GroupMember record is created for the public group Admins for the user
@isTest
static void test_updatePublicGroupUsers_active() {
Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];

Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);
usr.IsActive = false;
insert usr;
// GroupMembers in the adminGroup before updation
List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
Set<Id> groupMembersIdsBefore = new Set<Id>();
for(GroupMember member : membersBefore) {
groupMembersIdsBefore.add(member.UserOrGroupId);
}
System.assertEquals(false, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should not be present for the inserted user.');
// Make the user active by updating IsActive checkbox true
Test.startTest();
usr.IsActive = true;
update usr;
Test.stopTest();
// Assert that the group member for public group Admins should be created for the user
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size() + 1, membersAfter.size(), 'Group Members count is same.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(true, userIdsSet.contains(usr.Id), 'GroupMember should be created for the inserted user.');
}
// Verify that when an active user with profile System Administrator is made inactive, then a GroupMember record should be deleted for the public group Admins for the user
@isTest
static void test_updatePublicGroupUsers_inActive() {
Group adminGroup = [SELECT Id FROM Group WHERE DeveloperName = 'Admins' AND Type = 'Regular' LIMIT 1];

Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
User usr = TestUserUtil.createUser('Test', 'User', 'tusr', 'test.user444@apexstepbystep.com', adminProfile);
insert usr;
// GroupMembers in the adminGroup before updation.
List<GroupMember> membersBefore = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
Set<Id> groupMembersIdsBefore = new Set<Id>();
for(GroupMember member : membersBefore) {
groupMembersIdsBefore.add(member.UserOrGroupId);
}
System.assertEquals(true, groupMembersIdsBefore.contains(usr.Id), 'GroupMember should be present for the inserted user.');
// Make the user active by updating IsActive checkbox true
Test.startTest();
usr.IsActive = false;
update usr;
Test.stopTest();
// Assert that the group member for public group Admins should be deleted for the user
List<GroupMember> membersAfter = [SELECT Id, UserOrGroupId From GroupMember Where GroupId = :adminGroup.Id];
System.assertEquals(membersBefore.size() - 1, membersAfter.size(), 'Group Members count is same.');
Set<Id> userIdsSet = new Set<Id>();
for(GroupMember member : membersAfter) {
userIdsSet.add(member.UserOrGroupId);
}
System.assertEquals(false, userIdsSet.contains(usr.Id), 'GroupMember should be deleted for the user.');
}
}
Code Coverage: 100%
Like it ? Share : Do Nothing

Leave a Reply