Skip to content

Instantly share code, notes, and snippets.

@SalesforceBobLightning
Last active September 5, 2018 16:24
Show Gist options
  • Select an option

  • Save SalesforceBobLightning/ca0691278bac2a73f54c078d8336acb5 to your computer and use it in GitHub Desktop.

Select an option

Save SalesforceBobLightning/ca0691278bac2a73f54c078d8336acb5 to your computer and use it in GitHub Desktop.
Salesforce Lightning JavaScript Helper method for calling an Apex Controller method
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);
})();
},
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