Search code examples
triggerssalesforceapexsoql

Salesforce after Update Trigger


I have created the following after update trigger but I am unable to have it to save, I don't quite undetstand why it does not work

trigger Adhoc_Approval_process_trigger on Ad_Hoc_Approval__c (after update) {

    list<Ad_Hoc_Approval__c> ladh= new list<Ad_Hoc_Approval__c>(); 
    list<Ad_Hoc_Approval__c> query=[select Status__c,Submitted_for_Approval_Date__c from Ad_Hoc_Approval__c];
    for(Ad_Hoc_Approval__c adh : query)
    {
        if(adh.Status__c =='Submitted for Approval')
        {
            adh.Submitted_for_Approval_Date__c=Date.today();
            ladh.add(adh);
        }

    }

    update ladh;

}

I have also converted it to a before update trigger, and it's working fine, can anyone please help me understand why,

trigger Adhoc_Approval_process_trigger on Ad_Hoc_Approval__c (before update) {

        for(Ad_Hoc_Approval__c adh : trigger.new)
        {
            if(adh.Status__c =='Submitted for Approval')
            {
                adh.Submitted_for_Approval_Date__c=Date.today();

            }

        }



    }

Thanks a lot


Solution

  • You mean fails to save as it doesn't compile? Hm, looks good at a glance, got any errors?

    Your 1st version would end up being a neverending loop :) update -> update -> update... Not to mention the query doesn't have any WHERE clause so it would eventually explode anyway once you reach 10,0001 records...

    2nd version is much better :) Works only on current trigger's scope and "before update" you get the save to database for free.