How to run the execute controller method during [removed] event?

207    Asked by DavidEdmunds in Salesforce , Asked on May 1, 2023
 I have a visualforce page that runs calculations and stores them in an sObject as "temporary" until a user clicks a Save button, which removes the temporary flag. This was done because the calculations take longer than the max CPU time limit available, and a batch process does the calculations while the page polls for results to be completed.


My issue is that when a user doesn't save the records, and navigates away from the page (clicks any link, closes the window, etc), I want to delete the temporary records.

I've tried doing JS Remoting like this, but it didn't work:

[removed] = function() {
    // delete the temporary records.
    Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.MyController.deleteTemporaryRecords}','{!reportId}',handleResult);
    console.log('deleting temporary records. {!reportId}');
}
I've also tried the different syntax for JS Remoting like this:
[removed] = function() {
    // delete the temporary records.
    MyController.deleteTemporaryRecords('{!reportId}',handleResult);
    console.log('deleting temporary records. {!reportId}');
}
I've also tried using an actionFunction inside the apex:Form

    

[removed] = function(){
    deleteTemporaryRecords();
};
I also tried calling a @future method from my controller method so that the delete happens asynchronously, but that hasn't worked either.

Has anyone been able to successfully run a controller method during [removed] or [removed] events?

Answered by Aashna Saito

I suggest you update your onbeforeunload to return null; like so:


[removed] = function() {
    // delete the temporary records.
    MyController.deleteTemporaryRecords('{!reportId}',handleResult);
    console.log('deleting temporary records. {!reportId}');
    return null;
}

That said, I would be very wary of this approach. Clients will not necessarily fire this event, so you shouldn't depend on it to delete the temporary records. Instead, I would probably run a regular scheduled job to delete temporary records that were created > x minutes or hours ago.



Your Answer

Interviews

Parent Categories