Saturday 26 July 2014

Call Apex Class from Custom Button (Javascript) in Salesforce

05:34


Most of the times, we end up needing to do more complex logic, but from the simplicity of the custom button on the page layout. This post aims at giving you a running start to this.

Lets get straight into it, by this we're assuming you know how to





Step 1  :  Lets first create the Apex class

Goto --> Setup --> Develop --> Apex Class --> Click "New"

Things to Remember: 
  • Class needs to be a Global class 
  • and the method you intend to call from the javascript must be a Webservice Method
e.g.

global class MyClass
{
    webservice static void myMethod() // you can pass parameters
    { 
         // Do something
    }
}

Step 2 : Now to setup the custom Button.


  • Goto --> Setup --> Object --> Buttons, links and Actions section
  • Click New Button or Link

  • Enter the Name of the button
  • Behaviour : Execute Javascript
  • Content source : On-Click Javascript
The Code Sample :

{!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}");
}



Things to remember

  • We use the sforce.apex.execute method which is part of the apex.js
  • if you have parameters to be passed in the method you can use e.g.

sforce.apex.execute("myClass","makeContact",
                             {lastName:"Smith",
                              a:account});

Advantage 
  • Javascript cannot usually be tested in salesforce, therefore using apex in AJAX it will be easier for you to test your business logic in apex class