apex to lightning

How to Convert sforce.apex.execute to Lightning | Salesforce Developer Guide


In this blog, we will learn how to directly call the apex class through a custom button or javascript button on the object detail page and how we can convert how we can do the same thing in Lightning.

Steps to Create Button

  1. Go to  Setup first, click Object Manager, then click Account.
  2. Click Buttons, Links, and Actions, then click New Button or Link.
  3. Name the button 
  4. Select Detail Page Button.
  5. Select Behaviour execute javascript and content source onclick javascript 
  6. Write the javascript code and save.

For this, we must remember some things before writing code or creating custom buttons:-

  1. The Apex Class must be declared as Global which we want to call inside javaScript code.
  2. Method should be webservice static method inside the class.
  3. The class must be declared as Global.

Syntax of Apex Class

// Non-parameterized
Global class ExampleApexClass{
    Webservice static void Method() {
        //write your logic here.
// Parameterized Method
Global class ExampleApexClass{
    Webservice static void testMethod(String objId){
        //write your logic here.

dont miss out iconDon't forget to check out: Using Batch Apex | Apex Developer Guide | Salesforce

Javascript code Syntax for Non-parameterized Method


JavaScript code Syntax  for parameterized Method

sforce.apex.execute("Class_Name","Method_Name",{objId: "{!object.Id}"});

Create a Lightning Component

sforce.apex.execute("Class_Name","Method_Name",{objId: "{!object.Id}"});
<aura:component implements="force:lightningQuickAction" controller="JSMMyExecuteClass" > 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

Create a controller

    doInit : function(component, event, helper) {
        var action = component.get("c.myExecuteMethodAura");
            "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();
                var urlRedirect = "https://www.google.com/search?q="+result;
                var urlEvent = $A.get("e.force:navigateToURL");
                    "url": urlRedirect
                console.error("fail:" + response.getError()[0].message); 

dont miss out iconCheck out another amazing blog by Kirandeep here: Learn All About Platform Events in Salesforce | The Developer Guide

In MyExecuteClass we need to create an equivalent method to call from our js

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


Popular Salesforce Blogs