0

I have a batch class that should update the Contact phone number with Related Account Phone number.

But it is not working as it wont update the records. Please find my code below.

However there is no error with the code:

global class CustomBatch implements Database.Batchable<Sobject> {

    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        String query = 'select id,phone,Account.phone from Contact';
        system.debug('query');
        return Database.getQueryLocator(query);

    }
    global void execute(Database.BatchableContext bc,List<Contact> Scope){

        List<Contact> con = new List<Contact>();
        for(Contact c:con)
        {
            c.Phone = c.Account.Phone;
            con.add(c);
            system.debug('c');
        }
        update con;
    }

    global void finish(Database.BatchableContext bc){

        Messaging.SingleEmailMessage myemail = new Messaging.SingleEmailMessage();
        String[] toadd = new String[]{'[email protected]'};
           myemail.setToAddresses(toadd);
        myemail.setSubject('BatchCompleted');
        myemail.setPlainTextBody('Batch process has been completed successfully');
        Messaging.sendEmail(new Messaging.Email[]{myemail});
    }

}
0

2 Answers 2

2

Loop should be on List Scope, not List con in execute(). I would like to suggest below or similar execute() method instead.

void execute(Database.BatchableContext bc,List<Contact> Scope){

List<Contact> con = new List<Contact>();
for(Contact c:scope)
{
        c.Phone = c.Account.Phone;
        con.add(c);
        system.debug('c');
}
    update con;
}
3
  • #2 wasn't an issue; just changing the for loop to "scope" from "con" would have fixed the issue. Commented Feb 28, 2018 at 15:54
  • Oh my bad, Yeah. Thanks @sfdcfox , updated answer accordingly. Commented Mar 1, 2018 at 0:04
  • The extra list con is unnecessary; you can update the scope directly Commented Mar 1, 2018 at 6:06
2

You simply needed to loop over the correct variable. The second list was not necessary, either:

global void execute(Database.BatchableContext bc,List<Contact> Scope){
    for(Contact c: scope)
    {
        c.Phone = c.Account.Phone;
    }
    update scope;
}

Don't make extra work for yourself when you don't need to. You rarely ever need a second "update list" when you already have a list to start with.

I'm really not sure who that person is that keeps posting examples of copying to a new list, but it's rarely ever necessary, and just produces inefficient code.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.