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
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)
      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)
          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.
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:{}
  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]){
  for(Opportunity opp :{
    opp.Billing_Contact__c  = mapRoleContact.get(opp.AccountID+':Billing')
    opp.Shipping_Contact__c = mapRoleContact.get(opp.AccountID+':Shipping')