User Story
As a Salesforce administrator,
I want to mass update the UserRoleId
field to null for all users with existing roles,
so that I can reset user roles in bulk for further reassignment or role restructuring.
Apex Code
List<User> usersWithRoles = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
if (usersWithRoles != null && !usersWithRoles.isEmpty()) {
for (User u : usersWithRoles) {
u.UserRoleId = null;
}
update usersWithRoles;
}
Apex Class
public class UserRoleResetService {
// Method to reset UserRoleId for users with a role
public static void resetUserRoles() {
// Query to fetch users with a non-null UserRoleId
List<User> usersWithRoles = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
// Null check to ensure usersWithRoles list is not empty
if (usersWithRoles != null && !usersWithRoles.isEmpty()) {
// Set UserRoleId to null for each user
for (User u : usersWithRoles) {
u.UserRoleId = null;
}
// Perform bulk update on the modified users
update usersWithRoles;
}
}
}
Test Class
@IsTest
public class UserRoleResetServiceTest {
@TestSetup
static void setupTestData() {
// Create test users with UserRoleId set
List<User> testUsers = new List<User>();
for (Integer i = 0; i < 5; i++) {
User u = new User(
FirstName = 'Test',
LastName = 'User' + i,
Email = 'testuser' + i + '@example.com',
Username = 'testuser' + i + '@example.com',
Alias = 'tuser' + i,
TimeZoneSidKey = 'America/New_York',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1].Id,
LanguageLocaleKey = 'en_US',
UserRoleId = '00E000000000001' // Dummy role ID for testing
);
testUsers.add(u);
}
insert testUsers;
}
@IsTest
static void testResetUserRoles() {
// Call the method to reset UserRoleId
UserRoleResetService.resetUserRoles();
// Query the updated users to check if UserRoleId is set to null
List<User> updatedUsers = [SELECT Id, UserRoleId FROM User WHERE UserRoleId != null];
// Assert that no users have a non-null UserRoleId
System.assertEquals(0, updatedUsers.size(), 'UserRoleId should be null for all users');
}
}