How to convert sforce.apex.execute to Lightning

The idea is to convert a Salesforce Javascript button to Lightning Experience

Original JS button

{!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.uy';

We have to create a Lightning component:

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.uy/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);
  }
})

In JSMMyExecuteClass we need to create an equivalent method to call from our js controller:

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);
  }
}

Create a quick action that points to our component

Add the quick action to the layout(s)

Photo by Artem Sapegin on Unsplash

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s