Deep Diving in Salesforce Triggers II – Coderinme

In the last post we have discussed about the salesforce trigger, context variable and a sample code of trigger.In this post we will discuss more about events, understand the trigger line by line.
Salesforce Trigger

There are two type of salesforce trigger event’s.

Before Trigger : 

We use this event when we want to do some changes or do some validation before it is stored in database (but not  commited until the order of execution is finished). Example  before insert ,before update as before inserting, updating this record do this ( your logic ).

After Trigger :

 We use this event when we want to do some changes on some other records which can be related or not on the basis of currrent   inserted record. But we cannot do some modification on current record as it is being access in read mode only. Example after insert, after update create a new record of contact.

Now let’s talk about which salesforce trigger event’s  are applicable on which DML operations as salesforce fires these trigger on the specified object on specific DML operation’s  which are mentioned in salesforce trigger  event’s .

  • Insert : Both before and after trigger are applicable
  • Update : Both before and after trigger are applicable
  • Delete : Only before trigger is allowed not After trigger as trigger.new is not                          available as it has been deleted and moved to recycle bin.
  • Undelete : Only after trigger are allowed not before trigger as first data should  be moved from recycle bin then only we can perform any actions.

Now let’s just break and understand each part of trigger code.

Example : Suppose we want to  update Type__c of account on the basis of Type field of Account.

trigger updateType on Account ( before insert, before update ) {
    for( Account ac : Trigger.new ){
        if(trigger.isBefore && trigger.isInsert){
            if( ac.Type == 'Prospect' )
                ac.Type__c = 'Active';
            else
                ac.Type__c = 'Inactive';
        }
        else if( trigger.isBefore && trigger.isUpdate){
            if(ac.Type != Trigger.OldMap.get(ac.Id).Type)
                if( ac.Type == 'Prospect')
                    ac.Type__c = 'Active';
                else
                    ac.Type__c = 'Inactive';
            }
        }
    }
}

Explanation:

  • In the first line, the trigger is working on Account object of Salesforce and event as before insert, before update.

Please note, this trigger will only work for these 2 events before insert and before update.

  • Then a for loop is running which is fetching all the new records from trigger.new in Account variable ‘ac’.

Trigger.new can take maximum of 200 records for that object

  • Now we have 2 conditions 1 for insert and 1 for update
  • In insert , it checks the if condition i.e. if account type is ” Prospect” then this account will become active otherwise it is Inactive.
  • In the update logic it compare the new value of  Type with Old value of Type using Trigger.OldMap and then it updates the Type__c accordingly.

NOTE : if the business logic are same in both insert and update operation, we can combine events as.

if( ( trigger.isBefore && trigger.isInsert ) ||( trigger.isBefore && trigger.isUpdate ) ){

        for( Account ac : Trigger.new ) {

        if( ac.Type == 'Prospect' ) 
            ac.Type__c = 'Active'; 

        else 
            ac.Type__c = 'Inactive'; 
    
        }
    }

 

This functionality can be achieved using workflow

Note: Its a best practice to follow – One Trigger on One Sobject

which means only trigger should be implemented on one sObject which helps to debug and analyse trigger functionality.

If there are multiple trigger’s written on single Sobject then its hard to debug and analyse which trigger is firing on which condition and event.

Lets take another example where we add a validation error on the record on the basis of certain creteria.

Example : If a Account record Type__c is Active but its Active__c is not Yes then throw an error.

trigger updateType on Account ( before insert, before update ) {
         for( Account ac : Trigger.new ){

         if( ac.Type__c == 'Active' && ac.Active__c != 'Yes' )
              ac.Active__c.addError('Active field should be yes');

         else if( ac.Type__c == 'Inactive' && ac.Active__c!='No' )
              ac.Active__c.addError( 'Active field should be No');
       }
}

addError : It will throw an error message at the Salesforce UI or Data Loader                             when a record is being created or update and the entire dml  .operation will be roll back to previous database state.

Here it check the fields Type__c as Active but Active is Not yes then It will give error and show it on Page.

apex

NOTE: This functionality can be achieved using Validation rule.

As we have discussed,there will be one trigger for one Sobject. To implement this practice we need to create multiple helper class according to business logic in a single trigger (in upcoming post we will discuss about helper class ).

In the next post we will discuss about Use of collection in Trigger, Bulkify trigger and best practice.

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.