Loading

Call Apex Class methods from custom button or link

Data pubblicazione: Oct 13, 2022
Descrizione

To call an Apex class from 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. Use expression language to reference an action method. For example, action="{!doAction}" references the doAction() method in the controller. If an action isn’t specified, the page loads as usual. If the action method returns null, the page simply refreshes. This method is called before the page is rendered, and allows you to optionally redirect the user to another page.
Important: This action should not be used for initialization or DML.

Risoluzione

VisualForce page

<apex:page standardController="Case" extensions="EscalCase" action="{!caseEscalation}">
<apex:form>
<apex:inputHidden value="{!case.OwnerId}"/>
</apex:form>
</apex:page>

The above Visualforce page uses the standard controller of the Case object and extends its 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);
        pageRef.setRedirect(true);
       return pageRef; //Returns to the case page
    }
}
 
Numero articolo Knowledge

000385214

 
Caricamento
Salesforce Help | Article