Friday, October 26, 2012

Calling an APEX method from interface (like a button)

An Apex class is just a regular class.  Besides calling it from trigger or as a Visualforce controller, you should be able to call it directly from the frontend, such as when the user clicks a button.  There is a way to do that.

Say this is your standard class.

public MyClass
{
    public static String MyReply(String psInputA, String psInputB)
    {
        return psInputA + ' ' + psInputB;
    }

}

If you want to call the method from your button, you need to make some changes to the above class.  It has to be called as a webservice.  Basically what you need to do is to change the scope of the class to global, and indicate the method as a web service.  So the above needs to be changed to:


global MyClass
{
    webservice static String MyReply(String psInputA, String psInputB)
    {
        return psInputA + ' ' + psInputB;
    }
}

Now you can define your button action.  You can go to your object, create a new custom button (Create -> Objects -> [object name] -> Custom Buttons and Links.  You want to run a javascript, so select "Execute Javascript" in the Behavior picklist.  The code for your javascript should look like this:

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

var result = sforce.apex.execute("MyClass", "MyReply", {psInputA:"{!Invoice__c.Name}", psInputB:"YES"});

alert(result);

As you can tell, you can easily use expression statement to incorporate data.

Please try it and let me know if it works for you!

No comments:

Post a Comment

Please leave a comment.