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
ColaCola 

Trigger on Contact to Update Related Opportunity

Hi,

I'm trying to create a trigger that runs when a contact is created and updates the related Opportunity's location (City__c, State_Province__c, Country__c) (if the Opportunity's location is not populated yet) based on the contact's location. I have the following code but am getting errors: 

trigger updateOppLocation on Contact (after insert) {
    
    List<OpportunityContactRole> contactRoles = [SELECT OpportunityId,ContactId
                                                 FROM OpportunityContactRole
                                                 WHERE ContactId IN : Trigger.new];
    
    if(contactRoles.size()>0) {
        Map<Id,Id> conOpp_map = new Map<Id,Id>();
        
        for(OpportunityContactRole cr : contactRoles) {
            conOpp_map.put(cr.ContactId,cr.OpportunityId);
        }
        
        Map<Id,Opportunity> opp_map = new Map<ID,Opportunity>([SELECT Id 
                                                       FROM Opportunity
                                                       WHERE Id IN : conOpp_map.values()]);
        
        for(Contact c : Trigger.new) {
            if(conOpp_map.containsKey(c.Id)) {
                for (Opportunity o : opp_map) {
                   if (o.City__c == null && o.State_Province__c == null && o.Country__c == null) {
                      o.City__c = c.MailingCity;
                      o.State_Province__c = c.MailingState;
                      o.Country__c = c.MailingCountry;
                }
            }
        }
   	update opp_map;
    } 
}
The error I am receiving is: 
Loop must iterate over a collection type: MAP<Id,Opportunity>;

I am not sure if this is the best way to go about doing this, any help is appreciated. 
Deepak Kumar ShyoranDeepak Kumar Shyoran
Replace for (Opportunity o : opp_map) Line 20 with for (Opportunity o : opp_map.values())