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
Kon DeleKon Dele 

Issue with Field Populating Trigger

I have a custom field Sales Request that has 2 look up fields to Quote and Opportunity objects.

I'm trying to write a trigger that populates the Opportunity field when a Sales Request is created, but haven't been successful.

Any ideas on how to tweak my trigger below? Thanks!
trigger SalesRequestPopulateOpp on Sales_Request__c(Before Insert,Before Update) { 
    
    List<Id> qIds = new List<Id>();
    
      for(Sales_Request__c sr:trigger.new){

        if(sr.Quote__r.Id!=null){

            qIds.add(sr.Quote__r.Id);
           }
       }
    
  Map<Id,Quote> qMap = new Map<Id,Quote>([select id,Opportunity.Name
                                                     from Quote where id in:qIds]);
        
     for(Sales_Request__c srq :Trigger.new){
        
         if(!qMap.IsEmpty()){
    
                srq.Opportunity__c=qMap.get(srq.Quote__r.Id).Opportunity.Name;
      }            
    }
}


Jen BennettJen Bennett
I would recommend moving your if statement above the for loop since you are just saying is there anything in this map, then inside your for loop check to see if the map contains the quote id key, also you want to query for the opportunity id field and not the name since all lookups display a name but actually store the record id.
Anoop yadavAnoop yadav
Hi Kon,

You should use:  srq.Opportunity__c=qMap.get(srq.Quote__r.Id).OpportunityId;

instead of
srq.Opportunity__c=qMap.get(srq.Quote__r.Id).Opportunity.Name;

try the below code.
trigger SalesRequestPopulateOpp on Sales_Request__c(Before Insert,Before Update) { 
    
    List<Id> qIds = new List<Id>();
    
      for(Sales_Request__c sr:trigger.new){

        if(sr.Quote__r.Id!=null){

            qIds.add(sr.Quote__r.Id);
           }
       }
    
  Map<Id,Quote> qMap = new Map<Id,Quote>([select id,OpportunityId
                                                     from Quote where id in:qIds]);
        
     for(Sales_Request__c srq :Trigger.new){
        
         if(!qMap.IsEmpty()){
    
                srq.Opportunity__c=qMap.get(srq.Quote__r.Id).OpportunityId;
      }            
    }
}