function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Timothy SmithTimothy Smith 

Advice for Multiple Triggers on single Object (Case)

My company's org has about five triggers more than one existing (after insert, after edit).  I am about to create an (after insert) trigger.  Suggestions as to how I would consolidate or should I create my trigger and add to the pile.  If I should consolidate, how would that look?
Best Answer chosen by Timothy Smith
Deepali KulshresthaDeepali Kulshrestha
Hi Timothy,

1.You can see the best practice to write trigger from the below link:-

https://developer.salesforce.com/index.php?title=Apex_Code_Best_Practices&oldid=26951

2.Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

 1) One Trigger Per Object
 A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

 2) Logic-less Triggers
 If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

 3) Context-Specific Handler Methods
 Create context-specific handler methods in Trigger handlers

 4) Bulkify your Code
 Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

 5) Avoid SOQL Queries or DML statements inside FOR Loops
 An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

 6) Using Collections, Streamlining Queries, and Efficient For Loops
 It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

 7) Querying Large Data Sets
 The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

 8) Use @future Appropriately
 It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

 9) Avoid Hardcoding IDs
 When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
Trigger Example:

 trigger AccountTrigger on Account( after insert, after update, before insert, before update)

{

 

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);

     

    if( Trigger.isInsert )

    {

        if(Trigger.isBefore)

        {

            handler.OnBeforeInsert(trigger.New);

        }

        else

        {
            handler.OnAfterInsert(trigger.New);

        }

    }

    else if ( Trigger.isUpdate )

    {

        if(Trigger.isBefore)

       {

            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

        else

        {

            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

    }

Apex Class for trigger:-

public with sharing class AccountTriggerHandler
{

    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;

    public AccountTriggerHandler(boolean isExecuting, integer size)

    {

        m_isExecuting = isExecuting;
        BatchSize = size;

    }

    public void OnBeforeInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On Before Insert');

    }

    public void OnAfterInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On After Insert');

    }

    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');

        AccountActions.updateContact (newAccount);

    }

    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {

        system.debug('Account Trigger On Before Update ');

    }

 
  @future
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }     

    public boolean IsTriggerContext

    {

        get{ return m_isExecuting;}

    }
    public boolean IsVisualforcePageContext

    {

        get{ return !IsTriggerContext;}

    }

     

    public boolean IsWebServiceContext

    {

        get{ return !IsTriggerContext;}
    }
    public boolean IsExecuteAnonymousContext

    {

        get{ return !IsTriggerContext;}

    }

}

Create one Trigger Action Class

public without sharing class AccountActions
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

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

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Timothy,

Greetings to you!

A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.

If you have more than 1 trigger on 1 object, then there is no sequence in which these triggers will fire. There can be absolutely different sequences in which they are fired every time conditions are met.

Please refer to the below links which might help you further.

https://www.sfdc99.com/2015/01/19/the-one-trigger-per-object-design-pattern/

https://suscosolutions.com/salesforce-coding-ii-many-triggers/

https://developer.salesforce.com/blogs/developer-relations/2011/04/apex-trigger-tip-using-a-class-per-object-to-control-logic.html

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Deepali KulshresthaDeepali Kulshrestha
Hi Timothy,

1.You can see the best practice to write trigger from the below link:-

https://developer.salesforce.com/index.php?title=Apex_Code_Best_Practices&oldid=26951

2.Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

 1) One Trigger Per Object
 A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

 2) Logic-less Triggers
 If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

 3) Context-Specific Handler Methods
 Create context-specific handler methods in Trigger handlers

 4) Bulkify your Code
 Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

 5) Avoid SOQL Queries or DML statements inside FOR Loops
 An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

 6) Using Collections, Streamlining Queries, and Efficient For Loops
 It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

 7) Querying Large Data Sets
 The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

 8) Use @future Appropriately
 It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

 9) Avoid Hardcoding IDs
 When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
Trigger Example:

 trigger AccountTrigger on Account( after insert, after update, before insert, before update)

{

 

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);

     

    if( Trigger.isInsert )

    {

        if(Trigger.isBefore)

        {

            handler.OnBeforeInsert(trigger.New);

        }

        else

        {
            handler.OnAfterInsert(trigger.New);

        }

    }

    else if ( Trigger.isUpdate )

    {

        if(Trigger.isBefore)

       {

            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

        else

        {

            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

    }

Apex Class for trigger:-

public with sharing class AccountTriggerHandler
{

    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;

    public AccountTriggerHandler(boolean isExecuting, integer size)

    {

        m_isExecuting = isExecuting;
        BatchSize = size;

    }

    public void OnBeforeInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On Before Insert');

    }

    public void OnAfterInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On After Insert');

    }

    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');

        AccountActions.updateContact (newAccount);

    }

    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {

        system.debug('Account Trigger On Before Update ');

    }

 
  @future
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }     

    public boolean IsTriggerContext

    {

        get{ return m_isExecuting;}

    }
    public boolean IsVisualforcePageContext

    {

        get{ return !IsTriggerContext;}

    }

     

    public boolean IsWebServiceContext

    {

        get{ return !IsTriggerContext;}
    }
    public boolean IsExecuteAnonymousContext

    {

        get{ return !IsTriggerContext;}

    }

}

Create one Trigger Action Class

public without sharing class AccountActions
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

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

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
This was selected as the best answer