I would like to convert the following trigger to before insert/update (so that I don't have to include an "update lead" statement), but I'm not sure how to get the new value of the lead owner field if I do so:
trigger SetLeadOwnerManager on Lead (after insert, after update) {
List<lead> leadList = [SELECT TYPEOF Owner WHEN User THEN ManagerId END FROM Lead WHERE Id IN : Trigger.new];
system.debug('leadList: ' + leadList);
for (Lead lead: leadList) {
if(System.Trigger.oldMap.get(lead.Id).OwnerId != System.Trigger.newMap.get(lead.Id).OwnerId){
if (lead.Owner instanceof User) {
User userOwner = lead.Owner;
lead.Lead_Owner_Manager__c = userOwner.ManagerId;
update lead;
}
}
}
Attribution to: Rob Alexander
Possible Suggestion/Solution #1
You should not be requerying the records. You should be looping over Trigger.new and modifying those records:
List<lead> leadList = [SELECT TYPEOF Owner WHEN User THEN ManagerId END FROM Lead WHERE Id IN : Trigger.new];
for (Lead lead: leadList) {
Instead:
for (Lead aLead: Trigger.new){
EDIT: If you need that additional User data, Query separately for it and put it into a Map so that you can fetch it when needed.
Attribution to: dphil
Possible Suggestion/Solution #2
Do you need to check if the ownerId has changed on insert? Is there another trigger in play or a lead assignment rule that would be changing the owner ID?
Generally speaking, Trigger.oldMap
isn't applicable for an insert trigger as there are no old values to check against. Instead you can use Trigger.isInsert
to skip that test. See Trigger Context Variables
How about something like the following? It isn't as sexy without using the developer preview of the SOQL polymorphism feature, but it should get you close.
trigger SetLeadOwnerManager on Lead(before insert, before update)
{
Map<Id, Id> ownerMap = new Map<Id, Id>();
for (Lead lead : Trigger.new)
{
if(Trigger.isInsert ||
(System.Trigger.oldMap.get(lead.Id).OwnerId !=
lead.OwnerId)) {
// Queue if a new Lead or the OwnerId has changed.
ownerMap.put(lead.OwnerId, null);
}
}
if (ownerMap.size() > 0)
{
for (User[] users : [SELECT Id, ManagerId FROM User WHERE Id IN :ownerMap.keySet()])
{
for (User user : users)
{
ownerMap.put(user.Id, user.ManagerId);
}
}
for (Lead lead : Trigger.new)
{
// Should null be assigned here if the Owner isn't a user?
// This assignment should probably be skipped if the lead id isn't in the
// ownerMap keyset or you will null out the values when there is no change.
if(ownerMap.containsKey(lead.OwnerId)) {
lead.Lead_Owner_Manager__c = ownerMap.get(lead.OwnerId);
}
}
}
}
Attribution to: Daniel Ballinger
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34933