+ Start a Discussion
sudhirn@merunetworks.comsudhirn@merunetworks.com 

Trigger from Before Update to After Update

Hi, 

 I have a trigger which is created for before update event I need a similar logic for after update please suggest me how to change the trigger 
trigger auto_lead_assignment_update on Lead (Before update) 
{

  lead L;
  //Account A;
  String AID;
  Integer ledcnt;
  String rstate; 
  String rdomain;
  String rcompany;
  
  //List<lead> led = [select Email_Domain__c,state,company from lead where id = :Trigger.newMap.keySet()]; 
  
  L = [select Email_Domain__c,state,company from lead where id = :trigger.newmap.keyset() limit 1];    
  
  list<Account> A = new list<Account>();
  
  rstate = L.state;
  rdomain = L.Email_Domain__c;
  rcompany = L.company;
  
  
  if  ( L.state != NULL  && L.Email_Domain__c != NULL)
  {
  A = [select  Id,Email_Domain__c,OwnerId from account 
       where  
        BillingState = :L.state  and Email_Domain__c = :L.Email_Domain__c  limit 1 ];
        
    if(!(A.isempty()))
  {
        AID = A[0].Id; 
        for(lead ld : Trigger.new)
        {
            ld.Account__c = AID;  
            ld.run_assn_rules_yn__c = true;      
        }
  }
        
   }         
  else if  ( L.state != NULL && L.company != NULL)
  {
     A = [select  Id,Email_Domain__c,OwnerId from account 
       where  
           BillingState = :L.state  and name = :L.company limit 1 ];   
           
     if(!(A.isempty()))
  {
        AID = A[0].Id; 
        for(lead ld : Trigger.new)
        {
            ld.Account__c = AID;
            ld.run_assn_rules_yn__c = true;        
        }
  }        
  }       
  

}


Thanks

Sudhir

Antonio ManenteAntonio Manente
Well, this line:
 
L = [select Email_Domain__c,state,company from lead where id = :trigger.newmap.keyset() limit 1];

Is kind of unnecessary in a before trigger as the records havent been committed yet. That is typically behavior you'd see in an after trigger, so you're off to a good start! 

I didn't delve too much into the logic but as you said, that isn't changing much.. The only difference I could see is that you have to explicitly perform an update Dml operation. This is because in an after update trigger, the objects in (Trigger.new) have already been committed and are not editable. In order to change these values they must be re-queried and updated accordingly.