2

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;
}

2 Answers 2

1

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.

4
  • To whoever downvoted my answer, please explain WHY you downvoted it. Mar 28, 2014 at 6:22
  • Unique key automatically avoids race conditions, although it's impossible to control the resultant error.
    – sfdcfox
    Apr 26, 2014 at 4:49
  • I don't think that matters here. We want an error - and to prevent dml on those records. Apr 26, 2014 at 4:57
  • Unique key definitely, then.
    – sfdcfox
    Apr 26, 2014 at 4:59
0

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.

1
  • As the trigger fires for updates, I would assume that a query of existing SDR_Adjustment__c objects (created by the trigger for earlier inserts or updates) would be needed too.
    – Keith C
    Mar 26, 2014 at 19:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .