Wednesday, December 11, 2013

Before Delete Trigger in Salesforce

Scenario:
    
Write a Trigger on Account Object, All it does is to prevents the Delete of an Account if a particular field(i.e.,Client_ID__c) is not Null.

Trigger Code:


trigger AccountTrigger on Account (before delete) 
{ 
   if(System.Trigger.IsDelete)
   { 
     for (Account acc : trigger.old)
  {
    if (String.isNotBlank(acc.Client_ID__c))
     { 
  acc.addError('You cannot delete This Account Please contact your Salesforce.com Administrator for assistance.');
     }
         } 
   }
 }

Notes:

Trigger.oldReturns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers.
Trigger.isDeleteReturns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.

For more information/samples on trigger please check out here



Please comment or write us if you have any queries/requirements.

Please follow,bookmark,subscribe this site to receive daily updates.

Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks


Hope this helps you..Enjoy..!


1 comment:

  1. Hi Srinivas , I have code to prevent deletion of records -
    Code is -

    trigger delcheck on test_object__c (before Delete) {



    for(test_object__c mychl : trigger.old) {
    system.debug('step1');
    if(mychl.Opportunity__r.StageName =='Closed Won' ) {
    system.debug('step2');
    mychl.addError('You are not allowed to delete ');
    system.debug('step3');
    }



    }



    }

    from debug log , i got that step 2 is not working , can you please tell?

    ReplyDelete