2

I have a task where my frontend is giving me a json with the values. In the controller I have to convert the values into a String and save to the Roles__c field in the Stack__c object.

I never worked with remoteactions before, any help with this is highly appreciated!

Thanks.

0

1 Answer 1

1

Here is a very basic example, with no error checking that should get you close to what you need:

<apex:page controller="MyController">
  <script>
  function saveJSON(jsonData,recordId){
      var jsonString = JSON.stringify(jsonData);

      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.MyController.saveData}',
        jsonString,
        recordId,
        function(result, event) {
          alert(result);
        });
    };
  </script>
</apex:page>

Here is the controller code:

public class MyController{
    @RemoteAction
    global static String saveData(String jsonData, String recordId) {

        //get the stack we want to save.
        Stack__c s = [
            SELECT Id, Roles__c
            FROM Stack__c
            WHERE Id = :recordId LIMIT 1];
        s.Roles__c = jsonData;

        try {
            update s
        }catch (Exception e){
            return e;
        }
        return 'success';
    }
}

Notes: I've stringified the JSON from the webservice. This will mean you can pass it directly to the controller and save it straight to a field. If you need to process it, investigate JSON.deserialize and JSON.deserializeUntyped

You can pass as many variables as you need to the remote method. In this case, I've defined two - the json and the id of the record we want to save to.

Since RemoteAction methods need to be static, you have to pass in the id of the record you want to save - you can't get it from the controller instance state.

You probably need to check weather the result you get back in the first query is valid before trying to save the data to it.

Good luck!

0

You must log in to answer this question.

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