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
anvesh@force.comanvesh@force.com 

Duplicate records were creating while inserting contact Role on Opportunity?

I am trying to insert Contact Role on Opportunity. But with my trigger 2  same records were inserted. why and how to make it not allowing duplicate record ?

trigger Opportunity_Primary on Opportunity (before insert,before update, After Update) {
 
   List<OpportunityContactRole> OppContactRole = new List<OpportunityContactRole>();
    OpportunityContactRole ocr = new OpportunityContactRole();
   set<OpportunityContactRole> sid = new set<OpportunityContactRole>();

    for (Opportunity O : Trigger.new) {
        if (O.Contact_Name__c!=Null){
          
            ocr.OpportunityId = O.Id;
            ocr.ContactId = O.Contact_Name__c;
            ocr.IsPrimary = True;

            sid.add(ocr);  
            OppContactRole.addall(sid);      }
            
    }

    if(OppContactRole.size()>0)
    insert OppContactRole;

    }
Ajay K DubediAjay K Dubedi
Hi Anvesh,

You have made your trigger to run on both before Insert and before update  so its creating duplicate records.You can solve it by removing one from before insert and before update according to your need.

Thanks
Abhishek BansalAbhishek Bansal
Hi,

Please change your trigger code with below code :
trigger Opportunity_Primary on Opportunity (before insert,before update, After Update) {
 
	set<OpportunityContactRole> sid = new set<OpportunityContactRole>();
	OpportunityContactRole ocr;
	List<OpportunityContactRole> contactRoleList = new List<OpportunityContactRole>();
    for (Opportunity O : Trigger.new) {
        if (O.Contact_Name__c!=Null){
			ocr = new OpportunityContactRole();
            ocr.OpportunityId = O.Id;
            ocr.ContactId = O.Contact_Name__c;
            ocr.IsPrimary = True;
            sid.add(ocr);  
        }      
    }
	contactRoleList.addAll(sid);
    if(contactRoleList.size()>0)
		insert contactRoleList;

}
Let me know if you have any issue.

Thanks,
Abhishek