CloudyK Cloud Technology Talk, Tips, Tutorials.

14Jun/112

Super Easy Apex Batch to Fire Your Triggers

So I had a good conversation today with a fellow Salesforce developer regarding the different use cases for Batch Apex in Salesforce.  While there are a ton of complex uses, the following code sample is a really simple one that solves a persistent problem.

There have been countless times that I have written an Apex Trigger or developed a workflow rule that fires on a record update, and after completing it, I wanted to force it to fire on all records.  What I used to do was to export all of the records using the Apex Data Loader, then do another Data Loader Update job to invoke the trigger.  Sound familiar?  While this works, this is time intensive.

Batch Apex to the rescue!

Below is a "utility" class that I keep in my tool belt.  Its a fairly simple class that takes the Salesforce sObject name as a string in the constructor, then executes a Apex batch that updates all of the records.  It basically runs a "non-destructive" update by not changing any data.  I usually run this from the "Execute Anonymous" function within the debug log or from the same function within the Force.com IDE.  Here is the class...

global class InvokeUpdateTriggerBatch implements Database.Batchable<sObject> {

	private String sObjectName;

	global InvokeUpdateTriggerBatch(String sObjectName) {
		this.sObjectName = sObjectName;
	}

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

		String query = 'SELECT Id FROM ' + sObjectName;
		return Database.getQueryLocator(query);		

	}

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

		//Just update the records.  That's all!
		update scope;

     }

	global void finish(Database.BatchableContext BC){

   		System.debug('Batch Process Complete');

	}

}

Then to run the code, open up the Debug Log and run this...

InvokeUpdateTriggerBatch batch = new InvokeUpdateTriggerBatch('Lead');
Id batchId = Database.executeBatch(batch);

Keep this class handy because it makes this process of firing triggers and workflow rules really easy.

VN:F [1.9.14_1148]
Rating: 9.4/10 (14 votes cast)
VN:F [1.9.14_1148]
Rating: +1 (from 9 votes)
Super Easy Apex Batch to Fire Your Triggers, 9.4 out of 10 based on 14 ratings
Comments (2) Trackbacks (0)
  1. Excellent post.

    Can you give me some clarification How can we ensure our trigger executes through same batch class when we update bulk records from dataloader?

    • Vishal, it doesn’t execute the batch when you update via data loader. That’s the whole point: You don’t have to use Data Loader to update all your records.


Leave a comment

(required)

No trackbacks yet.