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
sudhirn@merunetworks.comsudhirn@merunetworks.com 

After Update After Insert

Hi, 

 I want to put below code inside after update after insert triger Please help me how to add below code into trigger am finding difficult in adding in inside trigger I need to pass trigger.new values in soql query.

Everytime when i make a update in lead it must look inside territory_lookup__c object to get values and update. 
 
for (lead ulds : [select id,postalcode,state,country from lead where id = '00Q180000029Ujz' limit 1])
 {
   ulds.postalcode = '';
   ulds.country = 'India';
   update ulds;
 }

 List<Territory_Lookup__c> territoryLookupList = null;  
 List<Integer> gzip = new List<Integer>(); // we need a list so that we can sort it.
 list<String> gstate = new list<String>();
 list<String> gcountry = new list<String>(); 
 
 for(Lead l :  [select id,postalcode,state,country from lead where id = '00Q180000029Ujz' limit 1]){
  gstate.add(l.state);
  gcountry.add(l.country);
  
   if ( l.postalcode != null)
   {
   gzip.add(Integer.valueof(l.postalcode));
   }
   else
   {
    gzip.add(0);
    }
 }

  system.debug('Zip :' + gzip);
  system.debug('State :' + gstate);
  system.debug('Country :' + gcountry);
 
  

  Territory_Lookup__c tls = [select Theater__c,Region__c,Area__c,User__c FROM Territory_Lookup__c
                           where  ( Zip_Start__c <= :gzip and Zip_End__c >=:gzip )  or
                                  (Country__c = :gcountry )
                                  limit 1]; 
    
  system.debug('Theater :' + tls.Theater__c);
  system.debug('Area :' + tls.Region__c);
  system.debug('Region :' + tls.Area__c);


  for(lead uld : [select id,postalcode,state,country from lead where id = '00Q180000029Ujz' limit 1]){
 
 
     uld.Territory_Lookup__c = tls.id;
     uld.Territory_Area__c = tls.Area__c;
     uld.Territory_Region__c = tls.Region__c;
     uld.Territory_Theater__c = tls.Theater__c;
 
      update uld;
   }

Thanks
Sudhir
Best Answer chosen by sudhirn@merunetworks.com
matt.ian.thomasmatt.ian.thomas
What is this code trying to do? It looks like you want to:
  • loop through trigger.new?
  • include some sort of information on those records based on fields that are filled out.
Generically, try something along these lines:
trigger CustomObjectTrigger on Custom_Object__c (before insert, before update) {

/** notice the contexts that I chose for this trigger. you mentioned that you wanted to put it
into an after trigger, but that would be a mistake since you would be unnecessarily
updating records again, causing recursion in your trigger. If you use the before context,
then you don't need to use dml; you can simply set the values and you're done. **/

if (trigger.isInsert) {
/** put any logic here for insert, if it somehow differs from updates **/
}
else if (trigger.isUpdate) {
/** this is the update context. you'll probably end up doing something like the below...**/
   List<String> valuesYouCareAbout = new List<String>();
   for (Custom_Object__c customObject : trigger.new) {
      /** you want to add all of the values of every record in the trigger here so you can
           get away with using just a single SOQL query for the entire transaction. **/
      valuesYouCareAbout.add(customObject.FieldYouCareAbout__c);
   }

   /** now you have a list of stuff you care about that you can use to grab those related
        objects that you want to relate to the records in your trigger. **/
   List<ObjectToRelate__c> objectsToRelate = [Select fields From ObjectToRelate__c Where FieldYouCareAbout__c IN: valuesYouCareAbout];

   /** now you have all of the records you want to relate to records in your trigger,
        so you can either use for loops to match them up, or build a map so you can
        just get them instead. **/
}

 /** no DML. just let the trigger end. **/
}

There are a couple of problems with the original code that you wrote that you should consider:
  • line 1, 13, and 43: you're executing the same SOQL query 3 times in one transaction. Throw the result into a variable one time and use that instead.
  • line 5 and 51: you're executing DML on the same record twice in the same transaction. This is related to the above point, and also the context comment I made in my example.
  • line 34: that will not compile because you can't use those operands on lists.

All Answers

matt.ian.thomasmatt.ian.thomas
What is this code trying to do? It looks like you want to:
  • loop through trigger.new?
  • include some sort of information on those records based on fields that are filled out.
Generically, try something along these lines:
trigger CustomObjectTrigger on Custom_Object__c (before insert, before update) {

/** notice the contexts that I chose for this trigger. you mentioned that you wanted to put it
into an after trigger, but that would be a mistake since you would be unnecessarily
updating records again, causing recursion in your trigger. If you use the before context,
then you don't need to use dml; you can simply set the values and you're done. **/

if (trigger.isInsert) {
/** put any logic here for insert, if it somehow differs from updates **/
}
else if (trigger.isUpdate) {
/** this is the update context. you'll probably end up doing something like the below...**/
   List<String> valuesYouCareAbout = new List<String>();
   for (Custom_Object__c customObject : trigger.new) {
      /** you want to add all of the values of every record in the trigger here so you can
           get away with using just a single SOQL query for the entire transaction. **/
      valuesYouCareAbout.add(customObject.FieldYouCareAbout__c);
   }

   /** now you have a list of stuff you care about that you can use to grab those related
        objects that you want to relate to the records in your trigger. **/
   List<ObjectToRelate__c> objectsToRelate = [Select fields From ObjectToRelate__c Where FieldYouCareAbout__c IN: valuesYouCareAbout];

   /** now you have all of the records you want to relate to records in your trigger,
        so you can either use for loops to match them up, or build a map so you can
        just get them instead. **/
}

 /** no DML. just let the trigger end. **/
}

There are a couple of problems with the original code that you wrote that you should consider:
  • line 1, 13, and 43: you're executing the same SOQL query 3 times in one transaction. Throw the result into a variable one time and use that instead.
  • line 5 and 51: you're executing DML on the same record twice in the same transaction. This is related to the above point, and also the context comment I made in my example.
  • line 34: that will not compile because you can't use those operands on lists.
This was selected as the best answer
Gyanender SinghGyanender Singh
Hi sudhirm,

Please use trigger.isinsert to the code you want to insert andd trigger.isupdate to the code block which you want to update.

Thanks
Gyani
http://www.mirketa.com
sudhirn@merunetworks.comsudhirn@merunetworks.com
Thank you very much I was able to achive this below trigger need a final help on creating a test class for below trigger can you suggest me how to drive the logic 
trigger after_territory on Lead (after insert,after update) 
{
 if(checkRecursive.runOnce())
 {
 Try
 {
 Set<Id> leadIds = new Set<Id>();
 List<Territory_Lookup__c> territoryLookupList = null;
 List<Integer> gzip = new List<Integer>(); // we need a list so that we can sort it.
 Set<String> gstate = new Set<String>();
 Set<String> gcountry = new Set<String>();

 for(Lead l :   Trigger.new){
  leadIds.add(l.id);
  gstate.add(l.state);
  gcountry.add(l.country);
   if ( l.postalcode != null)
   {
   gzip.add(Integer.valueof(l.postalcode));
   }
   if ( l.postalcode == null)
   {
   gzip.add(Integer.valueof(0));
   }
 }
 
 if ( trigger.isInsert || trigger.isupdate )
 {
   territoryLookupList =  [ select id,Area__c, Country__c, Region__c, State__c, Theater__c, User__c, Zip_End__c, Zip_Start__c
                          from Territory_Lookup__c
                          where ( Country__c = :gcountry) or
                                ( Zip_Start__c <= :gzip and Zip_End__c >=:gzip) or
                                ( Country__c = :gcountry and Zip_Start__c <= :gzip and Zip_End__c >=:gzip ) or
                                ( Country__c = :gcountry and State__c = :gstate)];
                                
  List<Lead> leds = new List<Lead>();
  
  if ( !territoryLookupList.isEmpty() )
  {
  for(lead uld : Trigger.new){                              
   lead  uleds = new lead( Id = uld.id,Territory_Lookup__c = territoryLookupList[0].id,
                           Territory_Area__c = territoryLookupList[0].Area__c,
                           Territory_Region__c = territoryLookupList[0].Region__c,
                           Territory_Theater__c = territoryLookupList[0].Theater__c);
   leds.add(uleds);
  }
    
   }  
  else
  {
   for(lead uld : Trigger.new){                              
   lead  uleds = new lead( Id = uld.id,Territory_Lookup__c = null,
                           Territory_Area__c = null,
                           Territory_Region__c = null,
                           Territory_Theater__c = null);
   leds.add(uleds);
  
   } 
  } 
   if ( leds.size() > 0) 
    {
     update leds;
     }
     
  }
}
catch (Exception e) {
List<Lead> leds = new List<Lead>();
for(lead uld : Trigger.new){ 
 lead  uleds = new lead( Id = uld.id,
                           Territory_Lookup__c = null,
                           Territory_Area__c = null,
                           Territory_Region__c = null,
                           Territory_Theater__c = null);
   leds.add(uleds);
  }
  update leds;
}  
  }
}

Thanks
Sudhir
Peter Kalina IBMPeter Kalina IBM
Hi Sudhir,

best practice is that if you are updating any kinds of records, create separate class that will be called from trigger. Give me few hours and i will past test class to you.

Thank you

Peter
sudhirn@merunetworks.comsudhirn@merunetworks.com
Hi Peter 

Thanks for you reply please send me a example of creating a seprate class and how to call that from trigget this will help me to resolve further issues. 

Thanks in Advance
Sudhir
Peter Kalina IBMPeter Kalina IBM
Hi Sudhir,

below you can find link to how to create apex class.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_class.htm

If you have your trigger already done please past it here. I would like to show you how to call class from trigger and how to make test class. You need to cover at least 70% of code.

Thank you

Peter