+ Start a Discussion
amitverma1195@gmail.comamitverma1195@gmail.com 

Query in batch class on lead based on user permission who submits the job?

we want to query on lead in batch class according to a particuler user sharing setting but as the the batch class run on system context it brings records globally, we want to query on lead in batch class based on the user who submitted the job and for a user who does not have all permisions on lead,lead is private for him.

College ManagementCollege Management
@Amit , By using triggerId of the job you can query ownerId of the job (i.e., the one who submitted the job) and then you can pass that ownerId to the batch class using parameterised contructor where you will query the lead records created by the same user who submitted the job. Below given might help you.

Schedule Class :

global class ScheduleBatchClass implements Schedulable {
    global void execute(SchedulableContext sc) {
        CronTrigger c = [SELECT Id, OwnerId FROM CronTrigger WHERE Id =: sc.getTriggerId()];
        BatchClass batch = new BatchClass(c.OwnerId);
        ID bId = Database.executeBatch(batch,5);
    }
}

Batch Class :

global class BatchClass implements Database.Batchable<Lead> {
    
    public List<ScheduledReport__c> query;
    public String owner;
    
    global BatchClass(String o) {
        owner = o;
    }

    global Iterable<Lead> start(Database.BatchableContext BC) {
        System.debug('oooooooooooooooo'+owner);
        query = [SELECT Id, Name FROM Lead WHERE CreatedById =: owner];// Here you are going to get the records createdby the user who submitted the job.
        return query;
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope) {
         //do something
     }
     global  void finish(Database.BatchableContext BC){
     }
}


If the above answer helped you , Please mark it as best answer so that it might useful for others looking for similar requirement.

Thanks !