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
kim.stiteskim.stites 

Apex Trigger for Opportunity for Contact Information

So I understand we cannot trigger off of the OpportunityContactRole object but someone said I could query the object and then update the opportunity.  I can't seem to figure out the best way to accomplish this.  I have some code that was given to me but I am not sure how I can then populate the opportunity with the contact ID.  Can someone please help?

trigger Contact_Role_Update on Opportunity (after insert) 
{Map<ID, OpportunityContactRole> roles = new Map<ID, OpportunityContactRole>([SELECT Id, Contact.Name, ContactId, IsPrimary, OpportunityId from OpportunityContactRole where OpportunityId in :opportunityidlist ]);

 

ClintLeeClintLee

You might try approaching it like this.  Basically, when new opportunities are inserted you loop through their contactroles and map the opportunity id to the primary contact id.  This way if there are multiple contact roles on an opportunity you will only be grabbing the primary person.  Then, loop through the opportunities in the trigger and pull the corresponding contact id from the map.

 

trigger Contact_Role_Update on Opportunity ( after insert ) {

              Map<Id, Id> oppToContactMap     = new Map<Id, Id>();

              List<Opportunity> oppsToUpdate = new List<Opportunity>();


              for( OpportunityContactRole ocr : [ select ContactId, OpportunityId, isPrimary from OpportunityContactRole where OpportunityId IN :Trigger.New ] ) {

                     if( ocr.isPrimary ) oppToContactMap.put( ocr.OpportunityId, ocr.ContactId );

               }

 

              for( Opportunity o : Trigger.New ) {

                    if( oppToContactMap.get( o.Id ) != null ) o.Contact_Id__c = oppToContactMap.get( o.Id );

                    oppsToUpdate.add( o );

               }

 

            update oppsToUpdate;

}

 

Hope that helps!

 

~ Clint

TbomTbom

Hi, I recently came up with a solution to the problem of no Opportunity Contact Role triggers.

See my reply on this thread:

http://boards.developerforce.com/t5/Apex-Code-Development/Apex-trigger-for-OpportunityContactRole-object/m-p/489963#M90384