This post contains different starting templates for starting coding. I have tried to include template for most of the common types of classes. It will help users to start easy coding and avoid repetitive typing of same template again and again. For beginner developers, it will help as a guide to study different types of classes and general structure.
Bookmark this page by pressing Ctrl + D, so that you can refer for common apex templates / syntaxes whenever you want.
Apex Class Version Header
It is a best practice to start apex classes and visualforce pages with proper starting version headers. Below template is useful for this.
/****************************************************************************
*Apex Class Name : Name of the class ehre
*Version : 1.0
*Created Date : 26 JAN 2015
*Function : One or two line description the class.
*
*Modification Log:
* Developer Date Description
* ----------------------------------------------------------------------------
* Author Name 01/26/2015 Original Version
******************************************************************************/
Apex Batch Class Template
Batch classes are used commonly in below scenarios,
- Process bulk data that cannot be processed in single execution due to governor limits
- Send email to multiple people from apex. Keep batch size 10 as salesforce allows only 10 outbound emails in single transaction
- Make more than 10 Future callouts. Here also keep batch size as 10 because salesforce allows only 10 future callouts in one transaction.
- If regular execution is hitting heap limit, usually we need to go for batch/future class. Regular heap limit is 6MB. But in batch or future classes we get 12MB as heap limit
global class Sample_BatchClass implements Database.Batchable {
String query;
global Sample_BatchClass() {
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List scope) {
//Execute method where operations are done over different batches
}
global void finish(Database.BatchableContext BC) {
//Finish method. It contains code that needs to be executed after all batches are complete
}
}
Apex Controller Extension Template
Controller extensions are used when we are overriding standard page layout with custom visualforce page for objects. Instead of sObject, respective object is used usually.
public with sharing class Sample_ControllerExtension {
private sObject mysObject;
// The extension constructor initializes the private member
// variable mysObject by using the getRecord method from the standard
// controller.
public Sample_ControllerExtension(ApexPages.StandardController stdController) {
this.mysObject = (sObject)stdController.getRecord();
}
}
Inbound Email Service Template
It is one of the very useful and less used feature in apex. Apex possess the capability to parse inbound emails and do operations like inserting record using the data in email etc. To use this you need to first create an inbound email service and email address. Thereafter whenever email is received in that email address, corresponding apex class will be executed. It can be used in below use cases,
- Share point integration. SharePoint can trigger emails, when articles are created using SharePoint work flows. In these emails contents need in salesforce can be added and sent to inbound email address. Inbound email class can parse this content and insert record in Salesforce.
- Email to Actions - It can be used to achieve salesforce record updates without logging into salesforce. For example, if you have some unique ID in opportunity and if you want to update opportunity status without logging into salesforce, we can create an inbound email service to accept status and unique ID in email subject and parse the email and update opportunity.
- Creating attachments - If you want to attach some records to salesforce record, you can avoid the need to download it, find record and attach it. It can be achieved by forwarding email to inbound email address and we can write class such that get record ID from subject and get all attachments in email and add to the given record ID.
global class Sample_EmailService implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env) {
// Create an InboundEmailResult object for returning the result of the
// Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String myPlainText= '';
myPlainText = email.plainTextBody;
result.success = true;
return result;
}
}
Webservice Callout
Usually if we need to integrate with some other systems or get data from other services, we will make http callout to the other system from apex. Below sample will show, how to make an http callout from apex.
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
//Usually below end point will be retrieved from custom setting
//It is because end point might vary from DEV,TEST,PROD Regions
String endpointURL = 'http://www.yourendpoint.com';
Http http = new Http();
req.setEndpoint(endPointURL);
req.setMethod('GET');
req.setTimeout(10000);
//If certificate name is different in different sandboxes,
//it should be kept in custom setting
req.setClientCertificateName(CertificateName);
try{
res = http.send(req);
}catch(Exception ex){
system.debug(ex.getMessage());
}
Parsing XML in Apex
Output of most of the webserivce calls will be a response with XML as body. Below code will show how to parse XML in apex which is response of a webservice call. (Assuming that variable res contains response of webservice call).
//Assuming res is the response of wevservice call with XML as body
Dom.Document documentObj= res.getBodyDocument();
//Getting the root element of the document.
Dom.XMLNode node= doc.getRootElement();
parseXMLNode(node);
//Method to parse XML Node, which will be called recursively
private String parseXMLNode(DOM.XMLNode node){
String parsedResponse='';
if (node.getNodeType() == DOM.XMLNodeType.ELEMENT)
{
if(node.getName().equalsIgnoreCase('type'))
{
system.debug('It is a type Node');
}
else
{
if (node.getText().trim() != '')
{
//Here iterate over different nodes in XML.
if(node.getName() == 'Node 1 Name')
{
parsedResponse += node.getText().trim();
}
else if(node.getName() == 'Node 2 Name')
{
parsedResponse += node.getText().trim();
}
}
//Below code checks for child nodes and calls the method again.
for (Dom.XMLNode child: node.getChildElements())
{
parseXMLNode(child);
}
return parsedResponse;
}
}
return ''; //should't reach here.
}