Activity Forums Salesforce® Discussions Writing a batch apex to update field

  • Prakhar

    Member
    April 26, 2016 at 8:27 am

    Hey,

    For the existing records the trigger does not works. If you want to achieve this using triggers only then you have to either manually update each record or the second choice would be to take a backup of all the records from data loader and then upsert the records back in Salesforce. Then your trigger will work and update the fields.

    But the best way is to run a batch class only once using developer console which would be getting all the records from the object on the created date basis and then update the fields in execute method. For example something like this:

    global class UpdateFieldForExistingRecord implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {

    String query = 'select id,name from account where createdDate < today';

    return Database.getQueryLocator(query);

    }

     

    global void execute(Database.BatchableContext BC, List<Contact> scope) {

    for(Account a : scope)

    {

    a.Name = a.Name + 'Updated';

    }

    update scope;

    }

    global void finish(Database.BatchableContext BC) {

    }

    }

    Hope that helps.

    Thanks.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos