[SalesForce] Workaround for ApexPages.currentPage() in schedulable class

A visualforce page controller uses ApexPages.currentPage().getParameters().get('id'); in its constructor.

I need to call this controller from apex schedulable class. So before creating instance i set page parameter as:

ApexPages.currentPage().getParameters().put('id',this.sid); but this is not working in schedulable class but this approach works in test class (therefore i used it in schedulable class).

//Code reference in schedulable
public void execute(SchedulableContext ctx)
{
    ApexPages.currentPage().getParameters().put('id',this.sid); // Exception: Attempt reference null        
    MyController con = new MyController();
}

Is there any workaround or need to change approach? Just want to know possibilities.

Best Answer

Fairly certain you'll need to change your approach. Fortunately this can be a quick refactor. Just extract your constructor into a method that takes the id param, then create a second constructor that also takes and id param, and wire it all up. You'll then be able to call it from your batch class without having to deal with re-testing the visualforce controller you tweaked.

Initial Constructor

public class MyController {
    private Id myId;

    public MyController() {
        myId = ApexPages.getCurrentPage().getParameters().get('id');
        ... stuff you don't want to touch ...
    }
}

Refactored

public MyController {
    private Id myId;

    public MyController() {
        init(ApexPages.getCurrentPage().getParameters());
    }

    public MyController(Id fromTestId) {
        init(fromTestId);
    }

    private void init(Id inputId) {
        myId = inputId;
        ... stuff you don't want to touch ...
    }
}
Related Topic