You need to sign in to do that
Don't have an account?
Apex Trigger Duplicate Insert Records
Hi all,
I got a problem about duplicate inserting child records.
The business requirement is: When a field value is changed, we want put the old value into custom history table just for tracking purpose.
So I wrote a trigger like below. TE_Sub_Task__c is custom parent object, Technical_Engagement_Comments__c is a custom child object of TE_Sub_Task__c, Comments__c is the field on parent object which we want to track.
Normally the trigger works well, but in one scenario, the trigger duplicates the records. The scenarios is the comments__c field got update, then workflow rules update other fields, then this trigger will be run again. So the same comments will be inserted twice. Does anybody know how to work around the problem? Hopefully I explain this issue clearly.
Any comments welcome.
trigger TESubTask_CommentUpdated on TE_Sub_Task__c (after insert, after update) {
List<Technical_Engagement_Comments__c> toBeInsert = new List<Technical_Engagement_Comments__c>();
for (TE_Sub_Task__c teSubTask : trigger.new){
if (teSubTask.Comments__c != null && teSubTask.Comments__c != ''){
if ((trigger.isInsert) || (trigger.isUpdate && trigger.oldMap.get(teSubTask.Id).Comments__c != teSubTask.Comments__c)){
Technical_Engagement_Comments__c teComment = new Technical_Engagement_Comments__c();
teComment.Comments__c = teSubTask.comments__c;
teComment.TE_Sub_Task__c = teSubTask.Id;
toBeInsert.add(teComment);
}
}
}
if (toBeInsert.size() > 0)
insert toBeInsert;
}
Try This changes
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.
Hi chamll, thanks for you reply. Unfortunately, it still doesn't work. The problem here is the trigger is run twice.
try to deactivate the workflow on the particular object n try once
Hi chamil, it still doesn't work. :(
I understand what you are trying to do. But the issue here is that some workflows updates field, which fire the trigger again. So basically, the trigger runs twice.
I am sure if I deactivate the workflow, it should work. But this is not the idea solution.
ya deactivate the workflow and again write a trigger which gives the same result as d workflow