Skip to content

Instantly share code, notes, and snippets.

@mchang-r7
Created January 28, 2018 18:16
Show Gist options
  • Save mchang-r7/45774e4e15838e1685191ab44006a57a to your computer and use it in GitHub Desktop.
Save mchang-r7/45774e4e15838e1685191ab44006a57a to your computer and use it in GitHub Desktop.
Reassign users from old user role to new user role with anonymous Apex
private class ReassignUserRoleJob {
private String oldUserRoleName;
private String newUserRoleName;
public ReassignUserRoleJob(String oldUserRoleName, String newUserRoleName) {
this.oldUserRoleName = oldUserRoleName;
this.newUserRoleName = newUserRoleName;
}
public void execute() {
List<User> affectedUsers = [
SELECT Id
FROM User
WHERE UserRoleId = :this.getUserRoleId(this.oldUserRoleName)
];
Id newUserRoleId = this.getUserRoleId(this.newUserRoleName);
for (User eachUser : affectedUsers) {
eachUser.UserRoleId = newUserRoleId;
}
update affectedUsers;
}
public Id getUserRoleId(String name) {
return name == null ? null : [
SELECT Id
FROM UserRole
WHERE Name = :name
].Id;
}
}
String oldUserRoleName = 'Old UserRole Name';
String newUserRoleName = 'New UserRole Name';
new ReassignUserRoleJob(oldUserRoleName, newUserRoleName).execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment