Friday 18 August 2017

Trigger Handler

What is the trigger handler : 

In a Salesforce context, a trigger handler is the starting point to 'handle' complex logic set into a trigger. Creating a class defined as MyObjectTriggerHandler can help to design a modular set of reusable objects which manage all the operations to be done by a trigger.

Ex. Suppose you want to write a simple code like update on same object.

Below is the trigger:

trigger Fieldupdate on Account (before insert , before update) 
{

 for(Account acc:trigger.new)
 {

 acc.Field_2__c = acc.Field_1__c;
 }

We will handle that trigger through class.

Handler class:

public class fieldupdate{

public void accfieldupdate(List<Account>listacc){

for(Account acc:listacc)
 {
   if(acc.Field_1__c==null){
   
   acc.adderror('Please fill the field');
   
   }
 }
}

}

Trigger:

trigger Fieldupdate on Account (before insert , before update) 
{

 fieldupdate handler = new fieldupdate();

 if(Trigger.isbefore || Trigger.isinsert &&  Trigger.isbefore || Trigger.isupdate){

 handler.accfieldupdate(Trigger.new);

 }


}


1.How to create a child to parent in trigger handler.


Handler class:

Public class accounttriggerhandler1{

List<Contact> needAccounts = new List<Contact>();
List<Account> newAccounts = new List<Account>();
Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();

public accounttriggerhandler1(list<contact>listcon)
{
for (Contact c : listcon) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }

}

public void accounttriggerhandler2(List<Contact> needAccounts)
{

if (needAccounts.size() > 0) {

        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts;

        for (Account a : newAccounts) {

            if (contactsByNameKeys.containsKey(a.Name)) {
                contactsByNameKeys.get(a.Name).accountId = a.Id;
            }
      }
    }
}

}

Trigger:

trigger acctrigger1 on Contact (before insert , before update) {

accounttriggerhandler1 accounthandler = new accounttriggerhandler1(trigger.new);

if(trigger.isbefore && trigger.isinsert || trigger.isbefore && trigger.isupdate)
{

accounthandler.accounttriggerhandler2(trigger.new);


}

}

3 comments:

One particular lead takes how many days to change it's stage from one stage value to another

/*************** Ceated By    : Mohit Dwivedi( KVP Business Solution Pvt Ltd) . Created Date :  Purpose      : This  controller is for Lead ...