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
Melissa ParkerMelissa Parker 

Workflow email alert to an Opportunity Contact

Im am trying to create a trigger that will update a Opportunity Lookup field to the contact to pull in the primary contact role if there is one on the Opportunity record. Once this is updated, then I would like to setup a workflow rule when upon Closed Won, an email will be sent to that Primary contact role. Does this make sense? Im struggling ....
Best Answer chosen by Melissa Parker
AMIT KAMBOJAMIT KAMBOJ
Below is the trigger code 
trigger CopyPrimaryContactToOptyTrigger on Opportunity (before update) 
{
   for (Opportunity o : Trigger.new) 
   {
       OpportunityContactRole[] contactRoleArray = [select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];
       if (contactRoleArray.size() > 0) 
       {
          
           o.Opportunity_contact__c = contactRoleArray[0].ContactID; // Amit you can Opportunity_contact__c to any lookup field you have
           
       }
   }
 }

 PS: you can create workflow rule. Its simple. 
 Please mark this as solution if this resolves the issue.

All Answers

AMIT KAMBOJAMIT KAMBOJ
Below is the trigger code 
trigger CopyPrimaryContactToOptyTrigger on Opportunity (before update) 
{
   for (Opportunity o : Trigger.new) 
   {
       OpportunityContactRole[] contactRoleArray = [select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];
       if (contactRoleArray.size() > 0) 
       {
          
           o.Opportunity_contact__c = contactRoleArray[0].ContactID; // Amit you can Opportunity_contact__c to any lookup field you have
           
       }
   }
 }

 PS: you can create workflow rule. Its simple. 
 Please mark this as solution if this resolves the issue.
This was selected as the best answer
Melissa ParkerMelissa Parker
Thank you Amit!!!