sforce.apex.execute in Lightning

sforce.apex.execute in Lightning

You are here because your JavaScript buttons that worked in Classic doesn’t work in Lightning.

Let see how you can make it work

Straight to the point

This is your JavaScript button that works in Classic

{!requireScript("/soap/ajax/20.0/connection.js")} 
{!requireScript("/soap/ajax/20.0/apex.js")}
 
sforce.apex.execute("JSMMyExecuteClass", "myExecuteMethod", {param1:"Im param1",param2:"Im param2"}); 
window.location = 'https://google.com';

And this is your button working in Lightning

JSMMyButton.cmp

<aura:component implements="force:lightningQuickAction" controller="JSMMyExecuteClass" >
  <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
</aura:component>

JSMMyButton.js

({
  doInit : function(component, event, helper) {
    var action = component.get("c.myExecuteMethodAura");
    action.setParams({
      "param1": 'Im param1',
      "param2": 'Im param2'
    });
    action.setCallback(this, function(response) {
    var state = response.getState();
 
    if(state == "SUCCESS" && component.isValid()){
      console.log("success") ;
      var result = response.getReturnValue();
      console.log(result);
 
      var urlRedirect = "https://www.google.com/search?q="+result;
      var urlEvent = $A.get("e.force:navigateToURL");
      urlEvent.setParams({
        "url": urlRedirect
      });
      urlEvent.fire();
    }else{
      console.error("fail:" + response.getError()[0].message); 
    }
  });
  $A.enqueueAction(action);
  }
})

JSMMyExecuteClass (Apex class)

public class JSMMyExecuteClass {
 
  public String myExecuteMethod(String param1, String param2){
    return 'ok '+param1+' - '+param2;
  }
 
  @AuraEnabled
  public static String myExecuteMethodAura(String param1, String param2){
    return new JSMMyExecuteClass().myExecuteMethod(param1, param2);
  }
}

The last step is to create a quick action that points to our component and then add it as many layouts you want.

Subscribe to this blog

Photo by lee junda on Unsplash