Salesforce Delegator to Run Batch

I was asked to implement a button to run a batch.
Firstly I decided to create a VisualForce page with a simple controller like this

<apex:page controller="rbc" >
<apex:pageMessage summary="The batch has been started. You will receive email when it completes." detail="" severity="INFO" strength="3" rendered="{!batchStarted}"/>
<apex:form >
<apex:commandButton action="{!x}" value="Run Batch to Do Something"/>
</apex:form>
</apex:page>
public class rbc {

public Boolean batchStarted { get; set; }

public PageReference x() {
Database.executeBatch( new BatchToDoSomething( ) );
batchStarted = true;
return null;
}

}

I presented this solution to the client, but the client told me that he would prefer a custom object button. I told him that if we implement a custom object button then we couldn’t easy configure which profiles should have access to this button, while if we use Visualforce page then we could easily setup profiles access to the page. He told me that we wants profile to be checked in button javascript code.
So I had to create a global class with a simple method to run a batch.

global class Delegator {
webService static void runBatch( String name ){
Type t = Type.forName( name );
Database.Batchable<SObject> b = (Database.Batchable<SObject>) t.newInstance();
Database.executeBatch( b );
}
}

This time I decided to write a generic code to be able to run any arbitrary batch by passing batch class name to the method. And I created a button

{!REQUIRESCRIPT("/soap/ajax/37.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/37.0/apex.js")}
if (['00eC000000admin', '00eC000profile1', '00eC000profile2'].indexOf('{!$Profile.Id}') >= 0) {
sforce.apex.execute("Delegator","runBatch",{name:"BatchToDoSomething"});
alert("The batch has been started. You will receive email when it completes.")
} else {
alert('Sorry... :-(');
}

This time my client should be satisfied.

Advertisements
This entry was posted in apex, batch, button, controller, custom, javascript, Posts in English, Run, salesforce and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s