function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Priya 21Priya 21 

Custom Button That calls Apex class.

Hi,

I have an scenario in that we have to get record id as a parameter of the method of apex class. In apex class, it should performs update and delete operation of records for that particular record id. All these should be done while clicking the button in record page. Please give me some ideas how to call the apex class from custom button in lightning. 

AbhishekAbhishek (Salesforce Developers) 
To call an Apex class from the custom button or link on the object detail page, create a VisualForce page and call the Apex class method via the action attribute to make it work. Following is some sample code showing how to do that. The action method invoked when this page is requested by the server.

In classic,
For calling apex class from the custom button the class must be global.
You can create a custom button from salesforce org using javascript.
Following the steps,
After creating an apex class (global).
Goto --> Setup --> Object --> Buttons, links and Actions section
Click New Button or Link
Enter the Name of the button
Behavior: Execute Javascript
Content source: On-Click Javascript
The sample js code for the button is


{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

if({!AAA__c.Name}!=Null)
{
    sforce.apex.execute("MyClass","myMethod",{}"});
    alert("This is {!AAA__c.Name}");
}



In Lightening:-

Create a lightning component that implements force:lightningQuickAction.
We can override our actions using this component.
Then we can call the apex class by setting our client-side controller to a callback function.

Use this code

var action = cmp.get("c.YourMethodName");
action.setParams({
     param1: cmp.get("v.something1"),
     param2: cmp.get("v.something2")
});
action.setCallback(this, function(response) {
   if (response.state === "SUCCESS"){
       var serverResponse = response.getReturnValue();
   }    
});
$A.enqueueAction(action);



For further reference, you can go through this official article too,

https://help.salesforce.com/articleView?id=000325250&type=1&mode=1


I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.