Print this page

How to call Apex Class methods from Customer Button or Link?

Knowledge Article Number 000006031

To call an apex class from custom button on link on the object detail page, developer would need to create a Visual Force 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.


Visual force page:
<apex:page standardController="Case" extensions="EscalCase" action="{!caseEscalation}">
<apex:inputHidden value="{!case.OwnerId}"/>
The above visual force page uses the standard controller of the Case object and extends it's functionality. This will enable us to get the Case record details. The Id is by default accessible to the Apex class. We have to include any other values we want the apex class to access as hidden fields as shown. The action attribute on the <apex:page> will call the apex class method and completes the processing.
Apex class:
public class EscalCase {
    //Apex properties or variables

    public Id owner {get; set;}
    public Id Id { get; set; }
    public Case cas { get; set; }

    //constructor to get the Case record
    public EscalCase(ApexPages.StandardController controller) {
    cas =  (Case) controller.getRecord();
    Id = cas.Id;
    System.debug('The case record: ' + cas);
    owner = cas.OwnerId;

    //Method that can is called from the Visual Force page action attribute
    public PageReference caseEscalation() {
       System.debug('Case Owner: ' + owner);
        System.debug('Case Id: ' + Id);
        //build your code logic here
       PageReference pageRef = new PageReference('/'+Id);
       return pageRef; //Returns to the case page

promote demote