trigger trig_Opportunity_CreateOppOwner on Opportunity (before update,before insert) {
List<id>OppsID = new List<id>(); //List that will hold all id of all new Opportunities owners
for(Opportunity Opp:Trigger.new){ //Loop that only retrives new versions of the Opportunity
if(trigger.isInsert)
OppsId.add(Opp.ID);
else if (trigger.oldMap.get(Opp.id).Op_Owner__c != trigger.oldMap.get(Opp.id).OwnerId)//trigger.isInsert and trigger.isUpdate added to account when it's null, avoids NullPointerException. Now all inserted opportunities are processed.
OppsId.add(Opp.ID);//adds all new opportunity owners to OppsId list. //Checks to see if they are new owners and not already on the owner list.
}
if(OppsID.size() <= 100)
List<Opportunity> oppsFromDb = [SELECT id, OwnerId FROM Opportunity WHERE id IN:OppsID];
for(Opportunity useOpps:oppsFromDb){
trigger.newMap.get(useOpps.Id).Op_Owner__c = useOpps.OwnerId;
}
The following trigger basically checks to see if OwnerId has been updated. If it has, it stores the new Owner in a custom field called Opp_Owner__c. However, the trigger seems to change only on odd numbered changes. For example:
- We change Owner. Op_Owner__C gets updated with the new Owner
- We change Owner again on the same opportunity. Op_Owner__c DOES NOT get updated with the second change on the owner we did.
- We Change Owner a third time on the same Opportunity. Now the Op_Owner__c gets updated to the third owner change we did.
Op_Owner__c
field in place just so that you can use it in formulas and whatnot? If so, Summer '13 introduces cross-object owner fields which may simplify your implementation.