I have created this trigger to add an adjustment record to the hours record when the hours record is created or update. How can I prevent duplicate records from being created?
Here is my trigger:
trigger SdrHotTracking on SDR_Hours__c (after insert, after update) {
Map<String, SDR_Hours__c> hour = new Map<String, SDR_Hours__c>();
for ( SDR_Hours__c h : Trigger.new )
{
hour.put( h.Alias__c, h );
}
List<SDR_Adjustment__c> newNotify = new List<SDR_Adjustment__c>();
for ( Opportunity List1 :
[ SELECT Id, Date_Qualified__c, Qualifier__c
FROM Opportunity
WHERE ( Qualifier__c IN :hour.keySet()
)
]
)
{
SDR_Hours__c hr = hour.get( List1.Qualifier__c );
newNotify.add
( new SDR_Adjustment__c
( Date_Worked__c = hr.Id,
Extension__c = hr.Extension__c,
Status__c = 'Submitted',
Reason_for_Adjustment__c = 'Hot',
Adjustment_Time__c = .50,
Opportunity_Name__c =List1.Id
)
);
}
insert newNotify;
}
Attribution to: Merry Stambaugh
Possible Suggestion/Solution #1
Create a Map with a String as the key. Populate the key from all of the items appended to each other that you are concerned about matching. Before adding a new record, do a .get from the map with those fields. If a null value is brought back then add a new record, otherwise don't.
Attribution to: dphil
Possible Suggestion/Solution #2
Create a field on the SDR_Adjustment__c object and in its properties, set it to unique. Then, when you make the new SDR_Adjustment__c record, set that field to whatever value will make it unique. When you insert your newNotify list, don't just type "insert newNotify." Type "Database.insert(newNotify, false)" so your non-unique records will fail insert silently.
Attribution to: DavidSchach
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31008