You need to sign in to do that
Don't have an account?
anvesh@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;
}
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;
}
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
Please change your trigger code with below code : Let me know if you have any issue.
Thanks,
Abhishek