[SalesForce] How to call a WebService method from a Lightning Component that replaces a Classic JavaScript button

We have JavaScript buttons that follow this pattern:

{!REQUIRESCRIPT('/soap/ajax/39.0/connection.js')}
{!REQUIRESCRIPT('/soap/ajax/39.0/apex.js')}

var ok = confirm('Create the Interest Adjustment?');
if (ok) {
    var result = sforce.apex.execute(
            'InterestRulesActions',
            'addInterestToPayment',
            {paymentId: '{!Payment__c.Id}'}
            );
    if ('success' == result) {
        // See the changes
        window.location.reload();
    } else {
        // See the error message
        alert(result);
    }
}

calling server methods of this nature:

global class InterestRulesActions {

    webservice static String addInterestToPayment(Id paymentId) {
        ...
    }
}

Such buttons are no longer rendered in Lightning Experience and so require rework if "Lightning Ready" status is to be maintained.

A Lightning Action that invokes a Lightning Component appears to be the way to go. Is the best (and maybe the only) way to directly re-use the server-side code to add @AuraEnabled to each method so it can be easily called from the Lightning Component:

global class InterestRulesActions {

    @AuraEnabled
    webservice static String addInterestToPayment(Id paymentId) {
        ...
    }
}

This compiles; does it work?

Best Answer

Components can only have one controller, so assuming this is a generic utility called all over the place, odds are, no, you won't be able to do this directly. If you look at force:recordData, you'll see that having a "generic" utility component that can interact with a particular service can be a viable design. You'd hook everything up with aura:method, and then you can call your service:

component.find("InterestRulesAction").addInterest(recordId, result => ...);

There's several ways you can design your API, but since you do need a call to the server, you'll need to specify a callback method so you can get the results later.


Since Lightning Session IDs don't have full API access, it shouldn't be possible to call the webservice method without @AuraEnabled. You will definitely need to call an @AuraEnabled method to (eventually) reach this method if choose to call it indirectly.

Related Topic