Last active
September 5, 2018 16:24
-
-
Save SalesforceBobLightning/ca0691278bac2a73f54c078d8336acb5 to your computer and use it in GitHub Desktop.
Salesforce Lightning JavaScript Helper method for calling an Apex Controller method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| callAction : function(cmp, methodName, params, callback){ | |
| var action = cmp.get(methodName); | |
| action.setParams(params); | |
| action.setCallback(this, function(response) { | |
| var state = response.getState(); | |
| console.log(methodName + ' ' + state); | |
| if(cmp.isValid() && state === "SUCCESS"){ | |
| var result = response.getReturnValue(); | |
| console.log(result); | |
| if (callback) callback(result); | |
| } else if (state === "ERROR"){ | |
| var errors = response.getError(); | |
| if (errors) { | |
| if (errors[0] && errors[0].message) { | |
| console.log(errors[0].message); | |
| } | |
| } | |
| } | |
| }); | |
| $A.getCallback(function() { | |
| $A.enqueueAction(action); | |
| })(); | |
| }, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| callAction : function(cmp, methodName, params, callback){ | |
| console.log(methodName); | |
| console.log(params); | |
| var action = cmp.get(methodName); | |
| action.setParams(params); | |
| action.setCallback(this, function(response) { | |
| var state = response.getState(); | |
| console.log(methodName + ' ' + state); | |
| if(cmp.isValid() && state === "SUCCESS"){ | |
| var result = response.getReturnValue(); | |
| console.log(result); | |
| if (callback) callback(result); | |
| } else if (state === "ERROR"){ | |
| this.handleErrors(response.getError()); | |
| } | |
| }); | |
| $A.getCallback(function() { | |
| $A.enqueueAction(action); | |
| })(); | |
| }, | |
| handleErrors : function(errors) { | |
| // Configure error toast | |
| let toastParams = { | |
| title: "Error", | |
| message: "Unknown error", // Default error message | |
| type: "error" | |
| }; | |
| // use the error message if any | |
| if (errors) { | |
| if (errors[0] && errors[0].message) { | |
| console.log(errors[0].message); | |
| toastParams.message = errors[0].message; | |
| } | |
| } | |
| // Fire error toast | |
| let toastEvent = $A.get("e.force:showToast"); | |
| toastEvent.setParams(toastParams); | |
| toastEvent.fire(); | |
| }, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment