This trigger will help you to avoid duplicate entries on the Junction object with the same set of parent records.
For Ex: Let's consider we have three objects Parent1, Parent2, and Child1(Junction Object between Parent1 and Parent2).
For Ex: Let's consider we have three objects Parent1, Parent2, and Child1(Junction Object between Parent1 and Parent2).
- We have inserted a record in Junction Object (CH1) with values as a parent1 record (P1) and Parent2 Record (P2).
- If we try to enter another Child record with again same parent combination i.e., P1 and P2 then the below trigger throw an error message saying duplicates not allowed.
Trigger:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | trigger AvoidDuplicateOnJunctionObject on Child1__c (before insert,before Update) {
set<Id> Parent1Set = new set<Id>();
set<Id> Parent2Set = new set<Id>();
Set<Id> AvailableParent1Set = new set<Id>();
set<Id> AvailableParent2Set = new set<Id>();
for(Child1__c vp : trigger.new){
Parent1Set.add(vp.Parent1__c);
Parent2Set.add(vp.Parent2__c);
}
for(Child1__c vp : [Select id, Parent1__c, Parent2__c from Child1__c WHERE Parent1__c IN: Parent1Set AND Parent2__c IN: Parent2Set]){
AvailableParent1Set.add(vp.Parent1__c);
AvailableParent2Set.add(vp.Parent2__c);
}
for(Child1__c vp : trigger.new){
if(AvailableParent1Set.contains(vp.Parent1__c) && AvailableParent2Set.contains(vp.Parent2__c)){
vp.adderror('Duplicate Combination Values are Not Allowed');
}
}
}
|
