+ Start a Discussion
Cal SteeleCal Steele 

Creating a trigger to set a lookup field to the Opportunity owner

I'm trying to set a custom Opportunity lookup field Sales Rep, which is a lookup to a custom Obj for Sales Reps, to the Opportunity Owner. Pretty new to triggers and would really appreciate any help. Here is where I'm at so far -
trigger SalesRepTrigger on Opportunity (after insert, after update) {
   
     if (trigger.isAfter) {
        if (trigger.isUpdate || trigger.isInsert) {
            
            Opportunity ops = new Opportunity();
            
            //get opporunity that triggered
            Set<ID> Ids = new set<id>();
            
            for(Opportunity o : Trigger.new){
               ids.add(o.Sales_Rep__c);
            }
            
            //get CC_Sales_Rep__c ids and store in Map
            //Map<Id, Id> RepMap = new Map<Id, Id>();
            
            Map<Id, CC_Sales_Rep__c> salesRep = new Map<id, CC_Sales_Rep__c>([Select id, OwnerId FROM CC_Sales_Rep__c
                                              Where CC_Sales_Rep__c =:ids]);
 
            //for(CC_Sales_Rep__c sr : salesRep) {
            //    RepMap.put(sr.Id, sr.OwnerId);
            //}
            
            //Get Opportunity Record Types
            Map<ID,Schema.RecordTypeInfo> rt_Map = Opportunity.sObjectType.getDescribe().getRecordTypeInfosById();
 
            for(Opportunity o : Trigger.new){
                //Only apply trigger to a certain record type
                if(rt_map.get(o.recordTypeID).getName().containsIgnoreCase('xxxx xxxx')){ 
                    ops.Sales_Rep__c = SalesRep.get(o.Sales_Rep__c).OwnerId;
 
                }
            }
         update ops;
        }
}
}
Best Answer chosen by Cal Steele
surya kanadhipatlasurya kanadhipatla
looks like in your test data does not have SalesRep.get(o.Sales_Rep__c).OwnerId was NUll(blank), 

Please try below updated code:



trigger SalesRepTrigger on Opportunity (before insert, before update) {   

     if (trigger.isbefore) {
        if (trigger.isUpdate || trigger.isInsert) {       

            //get opporunity that triggered
            Set<ID> Ids = new set<id>();   

            for(Opportunity o : Trigger.new){
            if(o.Sales_Rep__c!=Null)
               ids.add(o.Sales_Rep__c);
            }
      Map<Id, CC_Sales_Rep__c> salesRep = new Map<id, CC_Sales_Rep__c>([Select id, OwnerId FROM CC_Sales_Rep__c                                              Where CC_Sales_Rep__c =:ids]);          

            //Get Opportunity Record Types
            Map<ID,Schema.RecordTypeInfo> rt_Map = Opportunity.sObjectType.getDescribe().getRecordTypeInfosById();
  
            for(Opportunity o : Trigger.new){

                //Only apply trigger to a certain record type
                if(rt_map.get(o.recordTypeID).getName().containsIgnoreCase('xxxx xxxx')){
                
                if(salesRep.Containskey(o.Sales_Rep__c)
                {
                if(SalesRep.get(o.Sales_Rep__c).OwnerId!=Null)
                o.Sales_Rep__c = SalesRep.get(o.Sales_Rep__c).OwnerId;
                } 

                }

            }
      
        }
}

}

All Answers

surya kanadhipatlasurya kanadhipatla
Cal Steele,
Are you getting record read only error? Since you are trying to update opportunity (trigger.new) records(DML operation after insert/pdate) you will receive that error.

If yes, please change the trigger to before insert and before update and let us know if any other issues?
Cal SteeleCal Steele
No, I was getting the read only error on a previous version of the trigger. I have been attempting to modify it to prevent that though it has been very difficult for my skill level. I am now getting - Error: Invalid Data. Review all error messages below to correct your data. Apex trigger SalesRepTrigger caused an unexpected exception, contact your administrator: SalesRepTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.SalesRepTrigger: line 31, column 1 * = Thank you for any and all assistance!!!
Cal SteeleCal Steele
I'm sorry, it didn't save before I reran it. Not it runs without issue though it doesn't update the Sales_Rep__c field to the Opportunity Owner.
Cal SteeleCal Steele
The error noted above was when the trigger was after update, after insert.
surya kanadhipatlasurya kanadhipatla
looks like in your test data does not have SalesRep.get(o.Sales_Rep__c).OwnerId was NUll(blank), 

Please try below updated code:



trigger SalesRepTrigger on Opportunity (before insert, before update) {   

     if (trigger.isbefore) {
        if (trigger.isUpdate || trigger.isInsert) {       

            //get opporunity that triggered
            Set<ID> Ids = new set<id>();   

            for(Opportunity o : Trigger.new){
            if(o.Sales_Rep__c!=Null)
               ids.add(o.Sales_Rep__c);
            }
      Map<Id, CC_Sales_Rep__c> salesRep = new Map<id, CC_Sales_Rep__c>([Select id, OwnerId FROM CC_Sales_Rep__c                                              Where CC_Sales_Rep__c =:ids]);          

            //Get Opportunity Record Types
            Map<ID,Schema.RecordTypeInfo> rt_Map = Opportunity.sObjectType.getDescribe().getRecordTypeInfosById();
  
            for(Opportunity o : Trigger.new){

                //Only apply trigger to a certain record type
                if(rt_map.get(o.recordTypeID).getName().containsIgnoreCase('xxxx xxxx')){
                
                if(salesRep.Containskey(o.Sales_Rep__c)
                {
                if(SalesRep.get(o.Sales_Rep__c).OwnerId!=Null)
                o.Sales_Rep__c = SalesRep.get(o.Sales_Rep__c).OwnerId;
                } 

                }

            }
      
        }
}

}
This was selected as the best answer
Cal SteeleCal Steele
Thank you for the help, here is the code I ended at with your help! I now realize I should probably be using a handler but I'm not sure how to modify the code for that, any help you can give me would be greatly appreciated!! 
trigger OpportunityTrigger on Opportunity (before insert) {

//get IDs of club car opps that are new or owner changed
    Set<ID> oppOwnerIds = new set<id>();
    Id ccOppRecordTypeId = [SELECT Id FROM RecordType WHERE sObjectType='Opportunity' and DeveloperName='DevName'].Id;
    for(Opportunity o : Trigger.new){
        if((trigger.isInsert || o.OwnerId != trigger.oldMap.get(o.Id).OwnerId) &&
           o.RecordTypeId == ccOppRecordTypeId) {
            oppOwnerIds.add(o.Sales_Rep__c);
        }
    }
    if(!oppOwnerIds.isEmpty()){
        //get all the associated sales rep records
        Map<Id, Id> user2SalesRepMap = new Map<Id,Id>();
        for(CC_Sales_Rep__c rep : [SELECT Id, CC_Sales_Rep__c FROM CC_Sales_Rep__c WHERE CC_Sales_Rep__c in :oppOwnerIds]) {
            user2SalesRepMap.put(rep.CC_Sales_Rep__c,rep.Id);
        }
        if(!user2SalesRepMap.isEmpty()){
            //update sales rep lookup on opp
            for(Opportunity opp : Trigger.new){
                if(user2SalesRepMap.containsKey(opp.OwnerId)){
                    opp.Sales_Rep__c = user2SalesRepMap.get(opp.OwnerId);
                }
            }
        }
    }
surya kanadhipatlasurya kanadhipatla
Cal ,
Please see below:

1. Create Handler Class from Developer console with same name as below and replace the code  as below
===================================
Public class OpportunityTriggerHandler {
    //get IDs of club car opps that are new or owner changed
    Public static void updateSalesRepOnOpp (List<Opportunity> oppList,Map<Id, Opportunity>OldMap)
    {
        Set<ID> oppOwnerIds = new set<id>();
        
        Id ccOppRecordTypeId = [SELECT Id FROM RecordType WHERE sObjectType='Opportunity' and DeveloperName='DevName'].Id;
        
        for(Opportunity o : oppList){
            
            if(( o.OwnerId != oldMap.get(o.Id).OwnerId) && o.RecordTypeId == ccOppRecordTypeId) {
                
                oppOwnerIds.add(o.Sales_Rep__c);
                
            }
            
        }
        
        if(!oppOwnerIds.isEmpty()){
            
            //get all the associated sales rep records
            
            Map<Id, Id> user2SalesRepMap = new Map<Id,Id>();
            
            for(CC_Sales_Rep__c rep : [SELECT Id, CC_Sales_Rep__c FROM CC_Sales_Rep__c WHERE CC_Sales_Rep__c in :oppOwnerIds]) {
                
                user2SalesRepMap.put(rep.CC_Sales_Rep__c,rep.Id);
                
            }
            
            if(!user2SalesRepMap.isEmpty()){
                
                //update sales rep lookup on opp
                
                for(Opportunity opp : oppList){
                    
                    if(user2SalesRepMap.containsKey(opp.OwnerId)){
                        
                        opp.Sales_Rep__c = user2SalesRepMap.get(opp.OwnerId);
                        
                    }
                    
                }
            }
        }
    }
}
==============================================================
2. Update the existing trigger code as below:

==============================================

trigger OpportunityTrigger1 on Opportunity (before insert) {
OpportunityTriggerHandler.updateSalesRepOnOpp(trigger.new,trigger.oldMap);
}
surya kanadhipatlasurya kanadhipatla
Sorry, Trigger code as below:

trigger OpportunityTrigger on Opportunity (before insert) {
OpportunityTriggerHandler.updateSalesRepOnOpp(trigger.new,trigger.oldMap);
}