Friday, December 13, 2013

Run Execute Anonymous in Java Script for Custom List View Button

The application is required to run in schedule.I have Schedule class and Batch class.I call Batch class inside Scheduler like this

global class MySchedulerClass implements Schedulable{
    global void execute(SchedulableContext sc) {
       MyBatchClass c = new MyBatchClass ();
       Database.executeBatch(c, 5);
      
    }
}
But during development, I didn't schedule the job.I directly run in Apex Execute Anonymous like this:

MyBatchClass c = new MyBatchClass ();
       Database.executeBatch(c, 5);
So I can see the result quicker instead of waiting the job to be run on specific time. However there some request from the user to be able to run the Batch on the 'real' time using button.So I got an idea to just apply it as the same way I run in Apex Execute Anonymous.

Requirement
Steps:
1) Go to Setup -> Create -> Object . Choose the object you want to modify.Go to Buttons,Links and Action section.Click at New Button or Link.
2)Here you see the configuration for the button.Fill in necessary data as example below.
3)At the script field put the javascript code as below.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
 

  var scr="MyBatchClass c = new MyBatchClass (); " +
         " Database.executeBatch(c, 5); ";
  var result = sforce.apex.executeAnonymous(scr);
   alert("The Batch is Running");
Please note sforce.apex.executeAnonymous(scr); . src is variable that contain string of the Apex code that I run in Apex Execute Anonymous.

4) You're almost done.Now go to Search Layouts section.Click on Edit at Search Result.You will see Custom Buttons section, just move the button that you created to Selected Button.Then Save.

That's all you need.  Now it's done.The button should be display as requirement stated above.Dream come true, yay!!


References :  ExecuteAnonymous()

No comments:

Post a Comment