Skip to content

Instantly share code, notes, and snippets.

@scolladon
Last active May 10, 2016 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scolladon/6d6a68eef49748863d826d4fe7f25c77 to your computer and use it in GitHub Desktop.
Save scolladon/6d6a68eef49748863d826d4fe7f25c77 to your computer and use it in GitHub Desktop.
UserRoleInserter Salesforce
public class UserRoleInserter{
final private Map<String,String> roleNamePerParentRoleName;
public UserRoleInserter(){
this.roleNamePerParentRoleName = new Map<String,String>();
}
public void PutUserRoleHierarchy(final String aUserRole, final String aParentUserRole) {
this.roleNamePerParentRoleName.put(aUserRole,aParentUserRole);
}
public void InsertHierarchy(){
final map<string, UserRole> mUserRoles = new map<string, UserRole>();
for(string roleName : this.roleNamePerParentRoleName.keySet()){
final UserRole aRole = new UserRole(Name=roleName);
mUserRoles.put(aRole.Name,aRole);
}
insert mUserRoles.values();
for(UserRole aRole : mUserRoles.values()){
if(this.roleNamePerParentRoleName.get(aRole.Name) != null){
aRole.ParentRoleId = mUserRoles
.get(this.roleNamePerParentRoleName.get(aRole.Name)).id;
}
}
update mUserRoles.values();
}
}
@isTest
private class UserRoleInserterTest {
private static final string PARENT_ROLE = 'T1';
private static final string CHILD_ROLE = 'T2';
@isTest
private static void testInsertUserRole(){
final UserRoleInserter aURI = new UserRoleInserter();
aURI.PutUserRoleHierarchy(PARENT_ROLE,null);
aURI.PutUserRoleHierarchy(CHILD_ROLE,PARENT_ROLE);
final list<string> userRoleName = new list<string>{PARENT_ROLE,CHILD_ROLE};
for(UserRole aUserRole : [select id, parentid, name from UserRole where name in :userRoleName]){
if(aUserRole.name == PARENT_ROLE){
system.assert(aUserRole.parentid == null,PARENT_ROLE+' should not have a parent');
} else {
system.assert(aUserRole.parentid != null,CHILD_ROLE+' should have a parent');
}
}
aURI.InsertHierarchy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment