javascript button in salesforce

Invoke Apex Class From JavaScript Button in Salesforce

Introduction

In this blog, we will learn how to call an apex class from a custom button or the Javascript button from the object detail page directly.

For this, we have to remember some things before writing code or creating a custom button.

  1. The Apex Class which we want to execute Must be declared as Global.
  2. Method inside that class must be a web service static method.
  3. Method Can be parameterized and non-parameterized.

dont miss out iconDon't forget to check out: Schedular Class in Salesforce | Apex Developer Guide

Let's take an example of both parameterized and non-parameterized methods:

Syntax of Apex Class:

Global class TestClass{
    Webservice static void testMethod() //Webservice static void testMethod(String objId){
        //write your logic here.
    }
}

Syntax of Javascript code

For non-parameterized
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} 
sforce.apex.execute("Class_Name","Method_Name",{});
window.location.href="/{!object.Id}";
Parameterized
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} 
sforce.apex.execute("Class_Name","Method_Name",{"objId":'{! object.Name }'});
window.location.href="/{!object.Id}";

dont miss out iconCheck out another amazing blog by Anuj here: An Introduction to Salesforce Lightning Bolt Solution

Let's take a real example:

Apex Class:

global class approvalClass {
    webservice static void callApprovalprocess(Id Idd) { 
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments('Submitted');
        req1.setObjectId(Idd);
        Approval.ProcessResult res = Approval.Process(req1);                  
    }
}

Responses

Popular Salesforce Blogs