0

Is it possible to run batch apex from a custom button, I want to have a list button when I click it then I want to run the batch apex.

I know JavaScript button is possible since Lightning does not support javascript buttons, I am looking for other alternatives.

Can anyone help me out in this solution if possible.

1 Answer 1

2

It is possible to be done, but not directly through button, but with button + VF page + Apex Class. Here is what I mean:

1) Create Apex class (in my case TestClass) that collects selected records ids and run your batch:

public class TestClass {
    public List<String> ids; 
    public TestClass(ApexPages.StandardSetController controller) {
        this.ids = new List<String>();
        List<sObject> records = (List<sObject>) controller.getSelected();
        for (sObject record_i : records) {
            this.ids.add(record_i.Id);
        }
    } 

    public void runBatch() {
        //run your batch here with set of ids you have
        String query = 'SELECT Description, Id FROM Account WHERE Id IN (\'' + String.join(this.ids, '\',\'') + '\')';
        Database.executeBatch(new TestBatch(query), 20);
    } 
}

2) Create VF page (in my case TestPage) with standardController of the object you want to set your button for (in my case Account):

<apex:page standardController="Account" recordSetVar="records" extensions="TestClass" action="{!runBatch}"></apex:page>

3) Create Custom Button with below customization: enter image description here

4) Add button to List View Search Layout and use.

P.S.: as you can see, there is no just direct way without VF page step, however, you can add pop-up with message that batch has scheduled. I have also added my batch example to simplify the solution.

My TestBatch class:

public class TestBatch implements Database.Batchable<sObject> {
    public String query;
    public TestBatch(String query) {
        this.query = query;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(this.query);
    }

    public void execute(Database.BatchableContext bc, List<Account> scope) {
        for (Account acc_i : scope) {
            acc_i.Description = 'I was in batch';
        }

        update scope;
    }

    public void finish(Database.BatchableContext bc) {
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .