function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jasonkorjasonkor 

Trigger to update owner to "current user" upon case closed

I am trying to write a trigger to update the case owner to "current user" when the case is closed but I only want to do this for a particular role.  I believe the trigger below will update to current user on case close but I do not know how to limit it to a particular role.  Any help will be greatly appreciated.

 

trigger CaseUpdate on Case (before update) {
    if (Trigger.new.size() == 1) {  
        // if a Case has been updated to Closed
        if (Trigger.new[0].Status == 'Closed') {  
            // Change Trigger.old[0].OwnerId to Current User ID
            Trigger.new[0].OwnerId = UserInfo.getUserId();
        }
    }
}

Damien_2Damien_2

The following method call will give u the executing user's role.

 

UserInfo.getUserRoleId();

 

MoUsmanMoUsman

Hi jasonkor,

Let say you want update for CEO role then you can update using this apex code script,Here I have retrived role name (CEO) for the current user if qurey returns a record then this is right user for the update.

 

trigger CaseUpdate on Case (before update) {

User usersRoleName =[select Id, Name, UserRole.Name  from User Where Id=:UserInfo.getUserId() AND UserRole.Name ='CEO'];
    if (Trigger.new.size() == 1) {  
        // if a Case has been updated to Closed
        if (Trigger.new[0].Status == 'Closed' && usersRoleName != null) {  
            // Change Trigger.old[0].OwnerId to Current User ID
            Trigger.new[0].OwnerId = UserInfo.getUserId();
        }
    }
}
 
If you need for clarification so please reply.
----
Regards
Usman
Damien_2Damien_2

MoUsman, your code will actually cause a runtime error.  Might be better to do something like 

List<UserRole> roles = [SELECT Id FROM UserRole WHERE Id = :UserInfo.getUserRole()];

 

then later a check for 

if (roles.size() > 0)

 

MoUsmanMoUsman

Thanks Damien_2,For your catch and jasonkor please use this instead of above code. 

 

trigger CaseUpdate on Case (before update) {

List<User> usersRoleName =[select Id, Name, UserRole.Name  from User Where Id=:UserInfo.getUserId() AND UserRole.Name ='CEO'];
    if (Trigger.new.size() == 1) {  
        // if a Case has been updated to Closed
        if (Trigger.new[0].Status == 'Closed' && !usersRoleName.isEmpty()) {  
            // Change Trigger.old[0].OwnerId to Current User ID
            Trigger.new[0].OwnerId = UserInfo.getUserId();
        }
    }
}
 
Thanks

 

jasonkorjasonkor

Thank you for everyones help! I will now move on to sloppily writing a class for this trigger.  I appreciate your help