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
srikanthpallasrikanthpalla 

Trigger framework

Hi

please any tell me about Trigger Framework
Best Answer chosen by srikanthpalla
Amit Chaudhary 8Amit Chaudhary 8
Pleae check below post to know about trigger framwork and code:-
1) http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

According to trigger framework
1) we should create single trigger for each object.
2) One handler class which will call Action
3) Create one action class with business logic same function you can use for other activity also. You can call from VF page  or batch job if required.

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

Let us know if this will help you

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Pleae check below post to know about trigger framwork and code:-
1) http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

According to trigger framework
1) we should create single trigger for each object.
2) One handler class which will call Action
3) Create one action class with business logic same function you can use for other activity also. You can call from VF page  or batch job if required.

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

Let us know if this will help you
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Sample code for you:-

Example of Trigger Code :-

Create one Trigger "AccountTrigger"
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);
        }
    }
}
Create one Trigger Handler Class
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
    }
}
Please check below post for more help. Very good link
1) https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices
2) https://developer.salesforce.com/page/Apex_Code_Best_Practices

Let us know if this will help you

Thanks
AMit Chaudhary
 
Steve Cox 20Steve Cox 20
Here’s another option that has a much simpler architecture. Handlers can be deactivated at the feature, handler class, or “all” level. Activation can be specified according to individual user or profile. Also, it’s packaged for easy addition to any Salesforce org: the Apex BOOST Library (https://appexchange.salesforce.com/listingDetail?listingId=a0N4V00000IEUJvUAP&tab=e)
Amul Baranwal 17Amul Baranwal 17
1. Create a Trigger Handler Interface:
public interface TriggerHandler {
    void beforeInsert(List<SObject> newList);
    void beforeUpdate(List<SObject> newList, Map<Id, SObject> oldMap);
    void beforeDelete(List<SObject> oldList);
    void afterInsert(List<SObject> newList);
    void afterUpdate(List<SObject> newList, Map<Id, SObject> oldMap);
    void afterDelete(List<SObject> oldList);
    void afterUndelete(List<SObject> newList);
}

2. Create a Base Trigger Handler Class:

 
public abstract class OpportunityTriggerHandler implements TriggerHandler {
    public void beforeInsert(List<SObject> newList) {}
    public void beforeUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {}
    public void beforeDelete(List<SObject> oldList) {}
    public void afterInsert(List<SObject> newList) {}
    public void afterUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {}
    public void afterDelete(List<SObject> oldList) {}
    public void afterUndelete(List<SObject> newList) {}
}

3. Create Your Opportunity Trigger:
trigger OpportunityTrigger on Opportunity (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
    OpportunityTriggerHandler handler = new OpportunityTriggerHandler();

    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
            handler.beforeInsert(Trigger.new);
        }
        if (Trigger.isUpdate) {
            handler.beforeUpdate(Trigger.new, Trigger.oldMap);
        }
        if (Trigger.isDelete) {
            handler.beforeDelete(Trigger.old);
        }
    } else {
        if (Trigger.isAfter) {
            if (Trigger.isInsert) {
                handler.afterInsert(Trigger.new);
            }
            if (Trigger.isUpdate) {
                handler.afterUpdate(Trigger.new, Trigger.oldMap);
            }
            if (Trigger.isDelete) {
                handler.afterDelete(Trigger.old);
            }
            if (Trigger.isUndelete) {
                handler.afterUndelete(Trigger.new);
            }
        }
    }
}


4. Create Opportunity Trigger Handlers:
public class OpportunityValidationHandler extends OpportunityTriggerHandler {
    public void beforeInsert(List<SObject> newList) {
        // Implement validation logic for before insert
    }

    public void beforeUpdate(List<SObject> newList, Map<Id, SObject> oldMap) {
        // Implement validation logic for before update
    }
}