0

I wrote an Apex Trigger that would create a new record on a custom object whenever the Results__c picklist is set to 3 specific values. Everything seems to functional, but it always creates 2 records that are exactly the same. Any insight as to why would be great.

trigger createVendorRestriction on Opportunity (after update) {
List<Vendor_Exclusion__c> vend = new List<Vendor_Exclusion__c>();

for(Opportunity v : Trigger.new)
{

    if((v.Results__c == 'Product restricted at account type' || v.Results__c == 'Not a fit for this account' || v.Results__c == 'Lack of interest to work with vendor') && count == 0)
    {
        Vendor_Exclusion__c s = new Vendor_Exclusion__c(
        Name = v.Vendor_Name__c,
        Account__c = v.AccountId,
        Start_Date__c = Date.today(),
        Vendor__c = v.Vendor__c);
        insert s;

    }
}

}

3
  • you can also check this link help.salesforce.com/…
    – User6670
    Mar 19 '20 at 13:48
  • Are you entering two opportunities with the same vender and accountId? Have you made sure you arnt running into a recursion issue? What happens when you update just one opportunity? Mar 19 '20 at 14:37
  • 1
    Along with TSmith's answer below - if you have workflow that is updating the opp after you perform a manual update, the trigger will run again. See Order of Execution Mar 19 '20 at 15:29
2

Firstly, you need to remove the DML from the for loop. This will inevitably cause you additional platform limit issues in which you can confirm by unit testing.

I am unsure what count is used for as I do not see it declared within the shared code, so a compilation error is coming your way.

trigger createVendorRestriction on Opportunity (after update) {
    List<Vendor_Exclusion__c> vend = new List<Vendor_Exclusion__c>();

    for (Opportunity v : Trigger.new) {
        if ((v.Results__c == 'Product restricted at account type' ||
                v.Results__c == 'Not a fit for this account' ||
                v.Results__c == 'Lack of interest to work with vendor')
                && count == 0) {
            Vendor_Exclusion__c s = new Vendor_Exclusion__c(
            Name = v.Vendor_Name__c,
            Account__c = v.AccountId,
            Start_Date__c = Date.today(),
            Vendor__c = v.Vendor__c);
            vend.add(s)
        }
    }
    insert vend;
}

If you are still running into duplicate records, I suggest you extract a log file to understand where/what else the record is being inserted. There may be other declarative functions completing what you expect to only take place in Apex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.