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
Paul Foley4Paul Foley4 

What is the most efficient way to get the Manager's email address for the owner of a case?

I want to set up a trigger to populate a custom field with the email address of the Manager of the Owner of a Case. (if he exist)

I know I can do it with a formula on the custom field, however this is only works when the case is created. The case owner is going to change fairly regulary hence the need for a trigger (on case update). The second reason in need this as a trigger event is because we need the custom field to be a field type Email, so it can be used in our Milestone warnings (email alert)

 
Best Answer chosen by Paul Foley4
Veenesh VikramVeenesh Vikram
Something like this will be better:
trigger CaseTrigger on Case (before insert, before update) {
    Set<Id> ownerIds = new Set<Id>();
    for(Case c : Trigger.New)
    {
        //As manager exists only for user's and not queues/groups
        if(String.valueOf(c.ownerId).startswith('005')){
            ownerIds.add(c.ownerId);
        }
    }
    Map<String,String> ownersWithMgrEmail = new Map<String,String>();
    
    for(User u : [select id, managerId,manager.Email from User where Id in :ownerIds]){
        ownersWithMgrEmail.put(u.id, u.manager.Email);
    }
    for(Case c : Trigger.New)
    {
        if(ownersWithMgrEmail.size() > 0 && ownersWithMgrEmail.keySet().contains(c.ownerId)){
            c.Manager_Email__c = ownersWithMgrEmail.get(c.ownerId);
        }
    }
}

Hope this helps.

Best Regards
Veenesh

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
Balaji,

Your trigger is not bulkified. Avoid doing SOQL inside a for loop.
Veenesh VikramVeenesh Vikram
Something like this will be better:
trigger CaseTrigger on Case (before insert, before update) {
    Set<Id> ownerIds = new Set<Id>();
    for(Case c : Trigger.New)
    {
        //As manager exists only for user's and not queues/groups
        if(String.valueOf(c.ownerId).startswith('005')){
            ownerIds.add(c.ownerId);
        }
    }
    Map<String,String> ownersWithMgrEmail = new Map<String,String>();
    
    for(User u : [select id, managerId,manager.Email from User where Id in :ownerIds]){
        ownersWithMgrEmail.put(u.id, u.manager.Email);
    }
    for(Case c : Trigger.New)
    {
        if(ownersWithMgrEmail.size() > 0 && ownersWithMgrEmail.keySet().contains(c.ownerId)){
            c.Manager_Email__c = ownersWithMgrEmail.get(c.ownerId);
        }
    }
}

Hope this helps.

Best Regards
Veenesh
This was selected as the best answer
Paul Foley4Paul Foley4
Thanks Veenesh, that's exactly what I was after. :)