2

How can i make some class / method variable value persist between multiple remote method calls ?

I have a scenario where i need to call a remote action on click of a button multiple times. In between multiple clicks by user on this button, i want to store data in some variables. This will be used by subsequent calls.

i tried using class level static variables but it did not work.

3

RemoteAction methods are static, and can't store state; each transaction in Salesforce starts as a fresh slate, with nothing loaded in memory. You need to pass in any state you're interesting in keeping track of.

public class State {
    // members here
}
@RemoteAction public static State doSomething(State priorState) {
    if(priorState == null) {
        priorState = new State();
    }
    // Do stuff here, update priorState
    return priorState;
}

Then, you just need to store the state:

controller.doSomething( window.$stateVariable, 
    function(d, e) { window.$stateVariable = d; } );

The remoting framework will take care of the details for you, like JSON parsing, etc.

0

While the solution of @sfdcfox works, it relies on a sort of 'viewstate' to be passed to and from the client every call, which is a bit inefficient and/or error prone.

I think another way of doing this would be to use the Platform Cache to store the data serverside. You can use a Session Cache to store the required data between Javascript Remoting calls and get it from that same cache when you need it. The Session Cache is valid as long as the user (logged in) session is valid. You could also use the Org Cache (e.g. for anonymous pages).

Note that both Caches are not guaranteed to exist, they might be wiped, so there is a risk of a user experiencing problems, but I'm not sure how often this really happens in practice...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.