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
JustinWilliams2381JustinWilliams2381 

WHY IS THIS CODE CREATING DUPLICATE RECORDS!!!! HELP!

I wrote this code that once the opportunity is marked as "Closed Won" it is suppoed to clone the opp and primary contact role.  For some FRUSTERATING reason it almost always creates TWO clones instead of one and I can't figure out why.

 

trigger CreateGBRenewal on Opportunity (before update) {
try {

// List of opportunity IDs
Set<Id> oppIds = new Set<Id>();
//lists used for bulk
List<Opportunity> clonesToInsert = new List<Opportunity>();
List<OpportunityContactRole> RoleToInsert = new list<OpportunityContactRole>();

for( opportunity opp: Trigger.New){
if ((opp.StageName == 'Closed Won') && (opp.Subscription_Type__c == 'GradeBeam'||opp.Subscription_Type__c == 'GradeBeam for Subs' )&& (trigger.oldMap.get(opp.id).StageName != 'Closed Won' )){
oppIds.add(opp.Id);
}
}


for( opportunity oldOpp: [SELECT ID, accountId, account.name, Estimated_Renewal_Date__c FROM opportunity WHERE Id IN :OppIds]){

opportunity renewOpp = New opportunity();
renewOpp.closedate = oldOpp.Estimated_Renewal_Date__c;
renewOpp.AccountId = oldOpp.accountId;
renewOpp.name = oldOpp.account.name + ' Renewal';
renewOpp.stagename = 'Renewal Scheduled';
renewOpp.Type = 'Repeat Client';
renewOpp.RecordTypeId = '012S00000008r99';
clonesToInsert.add(renewOpp);
insert clonesToInsert;

for( opportunityContactRole OppCon: [SELECT ContactID, IsPrimary, Role FROM OpportunityContactRole WHERE OpportunityId IN :OppIds AND IsPrimary = TRUE]) {

OpportunityContactRole ConRole = New OpportunityContactRole();
ConRole.ContactID = OppCon.ContactID;
ConRole.OpportunityId = renewOpp.ID;
ConRole.IsPrimary = OppCon.IsPrimary;
ConRole.Role = oppCon.Role;
RoleToInsert.add(ConRole);
insert RoleToInsert;
}
break;
}
}catch (Exception e) {Trigger.new[0].addError(e.getMessage());}
}

Rahul SharmaRahul Sharma

JustinWilliams…,

 

Your code is not bulkified is first problem. You have a query and DML statement inside for loop which means while bulk load your trigger will definately fail.

Use Maps or Subquery to avoid queries inside for loop.. Collect records in list and perform dml on them outside FOR loop.

 

And the problem you are actually facing might be because of the following case :

 - workflow on Opportunity which is making you trigger to fire twice.

For getting rid of that, Try using Controlling Recursive Triggers to avoid firing your trigger for second time.

 

Hope it helps. Let us know if you face any furthur issues.