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
Vidhyasagar RanganathanVidhyasagar Ranganathan 

Trigger to update custom object with information from opportunity and contact role

Hi All,

I am looking for some help in writing a trigger that upon Opportunity creation (either from lead conversion or later) will get the contact ID from contact role and match that with the contact ID in the custom object to get Opportunity ID and update the custom object with opportunity fields.

Best Answer chosen by Vidhyasagar Ranganathan
Hi Vidhyasagar,

Below is the sample trigger code which I have written for you, with little modification (Custom object Name and the fields of it) code will work for you:
trigger on Opportunity (after insert, after update) {

 Map<Id, Opportunity> MapOfIdToOpp = new Map<Id, Opportunity>();
 Map<Id, Id> MapContactIdToOppId = new Map<Id,Id>();
 List<Test__c> lstTesttoUpdate  = new List<Test__c>();
 for(Opportunity opp : {
    MapOfIdToOpp.put(op.Id, opp);
 for(OpportunityContactRole OC : [Select Id, ContactId, OpportunityId from OpportunityContactRole Where OpportunityId IN=:MapOfIdToOpp.keySet() AND ContactId!=null] {  
     MapContactIdToOppId.put(OC.ContactId, OC.OpportunityId);  

// Query your custom object, I am assumung my custom object is Test__c. Opportunity__c and Contact__c are fields

for ( Test__c tc : [Select Id, Opportunity__c, Contact__c From Test__c Where Contact__c =:MapContactIdToOppId.keySet()]) {

   // I am update name and Opportunity__c field only, you can add own what all you need
   tc.Name = MapOfIdToOpp.get(MapContactIdToOppId.get(tc.Contact__c)).Name;
   tc.Opportunity__c = MapOfIdToOpp.get(MapContactIdToOppId.get(tc.Contact__c)).Id;


if (!lstTesttoUpdate.isEmpty()) {

  update lstTesttoUpdate;


Mark answer as solved if you have got your answer.