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
Nitin SharmaNitin Sharma 

apex class that update lead records using batch apex.

this is my code but its not woking. any one can help

global class LeadProcessor implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
          String query= 'SELECT Name, LeadSource from Lead';
        return Database.QueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        
        for(Lead l: scope){
            l.LeadSource ='Dreamforce';
           
        }
        update scope;
    }
    global void finish(Database.BatchableContext bc){
        
    }
}
Best Answer chosen by Nitin Sharma
BALAJI CHBALAJI CH
Hi Nitin Sharma,

Your code is perfect apart from one line. Try using database.getQueryLocator instead of Database.QueryLocator.
Please find the revised code.
global class PracticeAP implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        String query= 'SELECT Name, LeadSource from Lead';
        //return Database.QueryLocator(query);
        return Database.getQueryLocator(query); 
    }
    
    global void execute(Database.BatchableContext bc, List<Lead> scope)
    {
        for(Lead l: scope)
        {
            l.LeadSource ='Dreamforce';
            system.debug(l);
        }
        update scope;
    }
    
    global void finish(Database.BatchableContext bc)
    {
        
    }
}
Also find the below link to know the difference between database.getQueryLocator and Database.QueryLocator.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm

Please let me know if it helps you.

Best Regards,
BALAJI
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post for solution.
1) https://developer.salesforce.com/forums/?id=906F0000000D9AUIA0
 
global class LeadProcessor implements    Database.Batchable<Sobject> 
{
    global Database.QueryLocator start(Database.BatchableContext bc) 
    {
        return Database.getQueryLocator([Select LeadSource From Lead ]);
    }

    global void execute(Database.BatchableContext bc, List<Lead> scope)
    {
            for (Lead Leads : scope) 
            {
                Leads.LeadSource = 'Dreamforce';
            }
        update scope;
    }    

    global void finish(Database.BatchableContext bc){   }    
}
@isTest 
public class LeadProcessorTest 
{
    static testMethod void testMethod1() 
    {
        List<Lead> lstLead = new List<Lead>();
        for(Integer i=0 ;i <200;i++)
        {
            Lead led = new Lead();
            led.FirstName ='FirstName';
            led.LastName ='LastName'+i;
            led.Company ='demo'+i;
            lstLead.add(led);
        }
        
        insert lstLead;
        
        Test.startTest();

            LeadProcessor obj = new LeadProcessor();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
}
Let us know if this will help you

Thanks
Amit Chaudhary

 
BALAJI CHBALAJI CH
Hi Nitin Sharma,

Your code is perfect apart from one line. Try using database.getQueryLocator instead of Database.QueryLocator.
Please find the revised code.
global class PracticeAP implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        String query= 'SELECT Name, LeadSource from Lead';
        //return Database.QueryLocator(query);
        return Database.getQueryLocator(query); 
    }
    
    global void execute(Database.BatchableContext bc, List<Lead> scope)
    {
        for(Lead l: scope)
        {
            l.LeadSource ='Dreamforce';
            system.debug(l);
        }
        update scope;
    }
    
    global void finish(Database.BatchableContext bc)
    {
        
    }
}
Also find the below link to know the difference between database.getQueryLocator and Database.QueryLocator.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm

Please let me know if it helps you.

Best Regards,
BALAJI
 
This was selected as the best answer
Carlos FrancoCarlos Franco

Hi, not ure why, but when I run my test I cannot see any changes in the Lead Object... But the challenge is ok... Not sure if I am doing something wrong to test.. I added some displays, and I could see in Test Class that all inserts were ok... but when calls LeadProcessor, no record were processed 

(and no new records in Lead Object)

 

thanks in Advance

Carlos

BALAJI CHBALAJI CH
Hi Carlos,

Do you mean to say that the Lead Records which you inserted in Test Class are not visible in the Lead Object ?
And, is your Challenge Completed OR do you get any Error ?
Carlos FrancoCarlos Franco

Hi Bakajich, they are no visible in the Lead Object.

My challenge is completed... but I could not do a "real test".

BALAJI CHBALAJI CH
Hi Carlos,

Firstly, the records which are created in Test Class will not be visible in the Objects. These records which are inserted in Test Class will NOT be really inserted in the object. They are just used as Test data in the Test class for code coverage.
Secondly, to do the real test of the Batch class., you can insert few records in the Lead object directly and run the Batch class through Anonymous window.

1) To Insert Lead records, Go to Lead Tab -> Click New -> Provide required fieds -> Click Save.
User-added image
Insert few records like this. Do NOT give Lead Source value as 'Dreamforce'., since, when you run the Batch class, it will be updated to Dreamforce.

2) Run below code from Anonymous window:
LeadProcessor obj = new LeadProcessor();
DataBase.executeBatch(obj);
Open developer Console -> Debug -> Open Execute Anonylous Window
Copy & paste above code in the window and click on Execute.

User-added image

The batch class will execute and the Lead records which you inserted, their Lead Source will update to 'Dreamforce'

Let us know if you need any help.

Best Regards,
BALAJI

 
Carlos FrancoCarlos Franco

Hi Belaji, let me add the dispalys of my programs;

1) First I added displays in LeadProcessorTest to show the Insert was ok 

2) Display before the Update and I am counting how many recors were updaded

3) Display in FINISH to see how many records were displayed

Results

1) 14:51:53:243 USER_DEBUG [16]|DEBUG|lista Lead Inserted

2) 14:51:53:409 USER_DEBUG [18]|DEBUG|updated

3) 14:51:55:118 USER_DEBUG [24]|DEBUG|0 records

 

And finally I ran a query to check the table and nothing new 

 

Thanks in advance

 

Carlos

Surya236Surya236
APEX CLASS:
global class LeadProcessor implements Database.Batchable <SObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        String Query='Select id,LeadSource from Lead';
        return Database.getQueryLocator(Query);
            }
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l: scope){
            l.LeadSource='DreamForce';
        }
        update scope;
    }
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}
==============================================================================================================
APEX TEST CLASS:
@istest
private class LeadProcessorTest {
    @istest
    static void tetslead(){
        List<Lead> l= new List<Lead>();
        lead l1= new Lead();
        l1.LastName='surya';
        l1.Company='Company';
        l1.Status='Closed-Converted';
        l1.LeadSource='Dreamforce';
        l.add(l1);
        insert l;
    
    
    
    Test.startTest();
    LeadProcessor lp= new LeadProcessor();
    Id jobid= Database.executeBatch(lp);
    Test.stopTest();
    }
}
Sandeep YadavSandeep Yadav
My code is correct according to me but it shows an error on Line 1
Error: Compile Error: Class LeadProcessor must implement the method: System.Iterable<SObject> Database.Batchable<SObject>.start(Database.BatchableContext) at line 1 column 14

code--
global class LeadProcessor implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatachableContext BC){
        
        String query = 'select id,LeadSource from Lead';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Lead> scope){
        
        List<Lead> newLead = new List<Lead>();
        for(Lead l : scope){
            
            l.LeadSource = 'Dreamforce';
            newLead.add(l);
        }
        update newLead;
        
    }
    global void finish(Database.BatchableContext BC){
    
    }
}
Any help would be Thankful
Ben RowleyBen Rowley
Hello Sandeep, 
Please give this a go, let me know how you get on.
 
global class LeadProcessor implements Database.Batchable<sObject>{

    global integer recordsProcessed = 1;
    
    global Database.QueryLocator start(Database.BatchableContext bc){
       return Database.getQueryLocator('SELECT ID, LeadSource from Lead where LeadSource = \'Dreamforce\'');
    }
        
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l : scope){
      
            l.LeadSource = 'Web';
        }
        update scope;        
    }
          
	global void finish(Database.BatchableContext bc){
     System.debug(recordsProcessed + ' records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
       // EmailUtils.sendMessage(a, recordsProcessed);
    }     
}

TestClass:
 
@isTest
public class LeadProcessorTest {
	
     @testSetup
     static void setupLeads() {
        List<Lead> leads = new List<Lead>();
        // insert 200 accounts
        for (Integer i=0;i<200;i++) {
            leads.add(new Lead(company = 'testCompany' + i, 
                Leadsource='DreamForce', LastName = 'LeadingEdge' + i));
        }
        insert leads;
}
    
    @isTest
    static void testUpdateLeadBatch(){
        List<lead> leadsForUpdate =[select id, LeadSource from Lead where LeadSource = 'Dreamforce'];
        
        Test.startTest();
        LeadProcessor lp = new LeadProcessor();
        id batchJobId = Database.executeBatch(lp,200);
        Test.stopTest();
        
        List<lead> leadsAfterUpdate =[select id, LeadSource from Lead where LeadSource = 'Dreamforce'];
        System.debug(leadsAfterUpdate);
		System.assertEquals(0, leadsAfterUpdate.size());
        }
    }

 
Ben RowleyBen Rowley
You had spelt batchable wrong that's all :) 

in your code...

global Database.QueryLocator start(Database.BatachableContext BC){
        
Robin Bansal 35Robin Bansal 35
global class LeadProcessor implements Database.Batchable<sObject> {
    
    global Integer recordsProcessed = 0;
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator(
                'SELECT ID, Name, LeadSource FROM Lead');
    }
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        List<Lead> leads = new List<Lead>();
        for(Lead lead : scope){
            lead.LeadSource = 'Dreamforce';
            leads.add(lead);
        }
        update leads;
    }
    
    global void finish(Database.BatchableContext bc){
        System.debug('recordsProcessed for Leads = ' + recordsProcessed);
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
        //EmailUtils.sendMessage(a, recordsProcessed);
        
    }

}

@isTest
public class LeadProcessorTest {
    @testSetup
    static void setup(){
        List<Lead> leads = new List<Lead>();
        for(Integer i = 0; i<200; i++){
            leads.add(new Lead(lastname='Lead ' + i,
                               company = 'trailhead',
                              leadsource='Test Batch Apex'));
        }
        insert leads;
    }
    
    static testMethod void test(){
        Test.startTest();
        LeadProcessor leadProcess = new LeadProcessor();
        Id batchId = Database.executeBatch(leadProcess);
        Test.stopTest();
        
        System.assertEquals(200, [select count() from Lead Where LeadSource = 'Dreamforce']);
        
    }

}