+ Start a Discussion
Lisa KattawarLisa Kattawar 

Opportunity Trigger to update lookup field

I'm looking for a Trigger to do the following:

On Create Opportunity
Loop through Account Contacts (That's Contacts, NOT Contact Roles)
  If Contact.UserRole__c (a custom field on the contact object) = 'Billing'
      Store Contact ID in Opportunity.Billing_Contact__c (a custom lookup field on the Opportunity object)
  Else
      If Contact.UserRole__c (a custom field on the contact object) = 'Shipping'
          Store Contact ID in Opportunity.Shipping_Contact__c (a custom lookup field on the Opportunity object)
      Else
          ignore and go to next Account Contact

Thanks in advance!!  This is such a great Developer Community!  I'm not a developer but I can usually "modify" code if someone can get me started.
SrikanthKuruvaSrikanthKuruva
try the following and let me know. there can be syntax errors whic you might have to correct.

trigger updateContact on Opportunity(before insert){//this functions only during the create of the opportunity.
List<Id> listAccountIds = new List<Id>();

for(Opportunity Opp: trigger.new){}
  listAccountIds.add(Opp.AccountId);
}
if(!listAccountIds.isEmpty()){
  List<String> listContactUserRoles = new List<String>{'Billing','Shipping'};
  map<string,Id> mapRoleContact = new map<string,Id>();
  for(Contact c : [select Id, UserRole__c,AccountId from Contact where Accountid in :listAccountIds and UserRole__c in :listContactUserRoles]){
   mapRoleContact.put(c.AccountId+':'+c.UserRole__c,c.Id);
  }
  for(Opportunity opp : trigger.new){
   if(mapRoleContact.contains(opp.AccountID+':Billing'){
    opp.Billing_Contact__c  = mapRoleContact.get(opp.AccountID+':Billing')
   }
   if(mapRoleContact.contains(opp.AccountID+':Shipping'){
    opp.Shipping_Contact__c = mapRoleContact.get(opp.AccountID+':Shipping')
   }
  } 
}
}