+ Start a Discussion
Kishore Mudunuri 1Kishore Mudunuri 1 

Could any body explain before delete , after delete and after undelete with a usecase please?

pconpcon
Their usecases would depend on what you need to do with the data.  If you are manually calculating up a sum field (for example) you would want to re-calculate the value after an object has been deleted.  Similarly you would want to add it back in after the object is restored (undeleted).  The before / after would just depend on the type of action you are doing as to when it should be done.  The above would be an after delete, but in a before delete you may have apex logic that checks to make sure the object can be safely delete and if not then .addError to the record to prevent it from being deleted.
Ajay K DubediAjay K Dubedi
Hi Kishore,

You don't have to make things complicated here, It's simple as this

1. After triggers execute after the data has been inserted, updated or deleted in the database. So in case of 'after delete', if you query the data you may not find the data on which trigger has performed action. 

2. Before triggers execute before the data has been committed into the database. This means that if you decided to query the data it either would exist (in case of before delete) if it was an insert or if it’s being updated it would still be the previous values or no .

3. The after undelete trigger event only works with recovered records—that is, records that were deleted and then recovered from the Recycle Bin through the undelete DML statement. The after undelete trigger events only run on top-level objects. To see please refer: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_recovered_records.htm

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay DubediHi Kishore,

You don't have to make things complicated here, It's simple as this

1. After triggers execute after the data has been inserted, updated or deleted in the database. So in case of 'after delete', if you query the data you may not find the data on which trigger has performed action. 

2. Before triggers execute before the data has been committed into the database. This means that if you decided to query the data it either would exist (in case of before delete) if it was an insert or if it’s being updated it would still be the previous values or no .

3. The after undelete trigger event only works with recovered records—that is, records that were deleted and then recovered from the Recycle Bin through the undelete DML statement. The after undelete trigger events only run on top-level objects. To see please refer: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_recovered_records.htm

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi