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
Ramkumar MurugesanRamkumar Murugesan 

Trigger Code optimize

Hello all,

I have a requirement, where i need to create a record TSF in Account Related list whenever the territory is assigned to the account. Based on the territory name assigned to the account. I'm currently using this code. can you please optimize it.

Ex: Acccoun1 is having T1, T2. So i need the TSF records in the related list with the name of T1 and T2.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
    
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    system.debug('tobjlist--->'+tobjlist);      
    
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids]; 
    system.debug('acclist--->'+acclist); 
    
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
  
    for(Account aId : acclist){
     
      for(Territory  ter:tobjlist){
      
        List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c =:ter.Name and Account_vod__c =:aId.id Limit 1];
       
       if(existingTSFRecords.size()==0)
            {
           TSF_vod__c tsfRecord = new TSF_vod__c(Account_vod__c=aId.id);

            tsfRecord.Name = ter.name;
            tsfRecord.Territory_vod__c = ter.Name;
            System.debug('NEW TSF: ' + tsfRecord.Name);
            tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}



 
sandeep sankhlasandeep sankhla
Hi Ramkumar,

Toi optimize this you should not use SOQL inside for loop, also you should not use for inside for, try to use maps for optimizing it..Let me know if you need nay help on this...
Ramkumar MurugesanRamkumar Murugesan
Hi Sandeep,

I need your help on the points which you mentioned. 
  • Mapping Territory and Account ids 
  • I need to remove SQL query from the For Loop.
Please help me.
SF AdminSF Admin

Here ia the code:

 

trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
    
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    system.debug('tobjlist--->'+tobjlist);      
    
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids]; 
    system.debug('acclist--->'+acclist); 
    
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
    List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tobjlist.Name and Account_vod__c IN :acclist.id];
    
    
  
    for(Account aId : acclist){
     
        for(Territory  ter:tobjlist){
       
            if(existingTSFRecords.size()==0){
               TSF_vod__c tsfRecord = new TSF_vod__c(Account_vod__c=aId.id);

                tsfRecord.Name = ter.name;
                tsfRecord.Territory_vod__c = ter.Name;
                System.debug('NEW TSF: ' + tsfRecord.Name);
                tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}

Important :
If this is what you were looking for then please mark it as a "SOLUTION" or You can Click on the "Like" Button if this was beneficial for you.

Ramkumar MurugesanRamkumar Murugesan
Hi, 

I'm getting the below complie error.

Error: Compile Error: Initial term of field expression must be a concrete SObject: List<Territory> at line 47 column 145
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

// Query Account share records where the Territories changed manually

list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  

// query the Nestle holidays Record Type              
          RecordType rt=[select Id from RecordType where SObjectType = 'Account' and DeveloperName='Professional_vod' limit 1];
		  
		  
// Query Relatedid Using Usergroupid
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
 
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    system.debug('tobjlist--->'+tobjlist);      
    
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids AND RecordTypeId= :rt.Id]; 
    system.debug('acclist--->'+acclist); 
    
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
    List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tobjlist.Name and Account_vod__c IN :acclist.id];
    
    
  
    for(Account aId : acclist){
     
        for(Territory  ter:tobjlist){
       
            if(existingTSFRecords.size()==0){
               TSF_vod__c tsfRecord = new TSF_vod__c(Account_vod__c=aId.id);

                tsfRecord.Name = ter.name;
                tsfRecord.Territory_vod__c = ter.Name;
                System.debug('NEW TSF: ' + tsfRecord.Name);
                tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}

BR,
Ramkumar
sandeep sankhlasandeep sankhla
Hi RamKumar,

please replace the line no 47 with this

List<TSF_vod__c> existingTSFRecords = [SELECTAccount_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tobjlist AND Account_vod__c IN :acclist.id];
Ramkumar MurugesanRamkumar Murugesan
Hi, 


We have deployed the code, but it's not creating the recordss in the related list. can you please advise.

I hope the issue in  condition check. 

existingTSFRecords.size()== 0

We need to create it's not existing.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

    // Query Account share records where the Territories changed manually

    list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  

    // query the Nestle holidays Record Type              
          RecordType rt=[select Id from RecordType where SObjectType = 'Account' and DeveloperName='Professional_vod' limit 1];
          
          
    // Query Relatedid Using Usergroupid
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
 
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    set<String> tname= new set<String>();
    for (Territory t:tobjlist)
    {
        tname.add(t.Name);
    }

    set<id> accid= new set<id>();
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids AND RecordTypeId= :rt.Id]; 
    for (Account a:acclist)
    {
        accid.add(a.id);
    }
       
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
    
    List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tname AND Account_vod__c IN :accid]; 
    
  if(existingTSFRecords.size()== 0){
        for(Account aId : acclist){
     
           for(Territory  ter:tobjlist){
       
           // if(existingTSFRecords.size()==0){
               TSF_vod__c tsfRecord = new TSF_vod__c();

                tsfRecord.Name = ter.name;
                tsfRecord.Territory_vod__c = ter.Name;
                tsfRecord.Account_vod__c=aId.id;
                tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}

 
Ramkumar MurugesanRamkumar Murugesan
Hi , Can you please help me on the above comment.