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
Suraj DemgundeSuraj Demgunde 

We have region Field in Lead and i want Lead owner location value in that region field how i write class for that?

GhanshyamChoudhariGhanshyamChoudhari
Hi,
trigger leadownerloc on Lead (before insert,before update) {
    for(lead l:trigger.new){
        l.<regionFieldAPIName>=l.Owner.<Locationapiname>;
    }

}




Mark as best answer if it helps you.
Thanks,
Ghanshyam Choudhari
Suraj DemgundeSuraj Demgunde
ok but we have 2000 Leads and 20 Lead Owner total i want update all Leads based on user's location
Ajay K DubediAjay K Dubedi
Hi Suraj,

Please try the below code. Hope this helps you writing your apex class.

If you want for only active users then you fetch the active users using (IsActive=true)

public class LeadUpdateOwner {
    public static void updateLeadRegion()
    {
        List<User> UserList = new List<User>();
        UserList = [SELECT Id,Location__c FROM User];
        
        List<Lead> LeadList = new List<Lead>();
        LeadList = [SELECT OwnerId,Name,Region__c FROM Lead];
        
        List<Lead> updateLeadList = new List<Lead>();
        
        for(User u: UserList)
        {
            for(Lead led: LeadList)
            {
                if(u.Id == led.OwnerId)
                {
                    led.Region__c = u.Location__c;
                    updateLeadList.add(led);
                }
            }
        }
        if(updateLeadList.size()>0)
        {
            update updateLeadList;
        }
    }
}

Please mark it as best answer if you find helpful.

Thank You
Ajay Dubedi
GhanshyamChoudhariGhanshyamChoudhari
hi,
it seems like you need batch apex
global class batchClass implements Database.batchable{ 
   global Iterable start(Database.BatchableContext info){ 
    string query = 'select name,region__c, owner.Location__c from lead'; 
return Database.getQueryLocator(query); 
   }     
   global void execute(Database.BatchableContext info, List<Lead> scope){
       List<Lead> accsToUpdate = new List<Lead>();
       for(Lead a : scope){ 
           a.regionFieldAPIName__C= a.Owner.Location__c;            
           accsToUpdate.add(a); 
       } 
       update accsToUpdate; 
   }     
   global void finish(Database.BatchableContext info){     
   } 
}
To run batch Apex, go to User Menu --> Developer Console.
In the Apex Code section,
batchClass M = new batchClass ();
Database.executeBatch(M);