
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.
- The Apex Class which we want to execute Must be declared as Global.
- Method inside that class must be a web service static method.
- Method Can be parameterized and non-parameterized.
Don'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}";
Check 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