Pages

Monday, June 29, 2009

Triggering an Apex method with a Custom Button

Most often Salesforce.com developers want to write a custom logic such as sending a notification email, changing the status of a record (picklist), etc once a button is clicked on, in a standard layout.

The effort is minimized this way since you do not want to recreate the layout using a Visualforce page, all you need is to be able to launch a method once the button is clicked on.

In order to do so, you need to write your logic into an Apex class with following conditions:
  1. Firstly, your class should be marked as "Global"
  2. Secondly, the logic goes to a static method of this class which is marked as "WebService"
If an Apex class has the above characteristics, the method marked as web service can be called via javascript when the button is clicked on. Neat!

I think by now you have a good idea of where I am going with this, so let's dive into code and examine everything more closely.

Below I have created a Apex Class called "OutboundEmails" and added a method that has a keyword as "WebService".


global class OutboundEmails {

WebService static void SendEmailNotification(string id) {

//create a mail object to send a single email.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

//set the email properties
mail.setToAddresses(new string[] {'myemail@domain.com'});
mail.setSenderDisplayName('SF.com Email Agent');
mail.setSubject('A new reminder');
mail.setHtmlBody('an object with ID='+ id + ' is just clicked on.');

//send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail } );

}
}




This method receives an object Id (this is just to demo purposes, so you can identify any parameters that you need) and sends an email notification subsequently once the method is called.

Now let's concentrate on the button that will actually call our WebService method.

Firstly, I create a detail page button let's say on Account object and name it "Send Me ID".
This button's behavior will be "Execute Javascript".
If you need more information about how you can add a custom button to Account object please click here. Then I add the following code to the body of the button edit page:



{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
sforce.apex.execute("OutboundEmails","SendEmailNotification", {id:"{!Account.Id}"});
window.alert("Account Id is sent." );



Now It all works together!
Once you click on the button, in case you have not forgotten to change the sample email address with your own in the code, you should receive the email.