Apex/Visualforce common errors and how to fix

In this post we will discuss common errors that we will come across when using apex or visualforce and solutions to fix these common errors.

Apex Errors

  • System.NullPointerException: Attempt to de-reference a null object 
This is the most common error that everybody faces, if they are starting coding in apex without much prior experience in programming languages. This error occurs when user is trying to do some operation in null object. For example if you are trying to access a variable in an object instance it will give this error.

    Mostly this error is because of not considering null scenarios in coding. If you are facing this error, go ahead to the link mentioned in the error and make sure that the variable is not null. Once in the above code all variables are initialized properly, it will look like below,

Apex templates

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. 
    }    
 

Dynamically loading related content without controller in visualforce

In visualforce usually for loading additional content based on user actions, we use ajax and custom controllers. But if you are targeting to load details tab of some records, it can be done without using custom controllers or extensions. Please check the sample code below,


As mentioned previously this method helps you to show additional content through ajax without using controller. In order to use it please follow below steps
  • Create a visualforce page with some name (example - samplePage) 
  • Copy above code into the page and save the page
  • Create one account and some contacts under it.
  • Pass the ID of the account to the custom page (instance.com/apex/samplePage?id=0019000000BzKjL)
  • It will show the account name and contacts under the account.
  • Hover over any contact, it will show the details of the contact below.
Here we are making use of $currentPage global merge fieldtype. General syntax is $CurrentPage.Parameters.parameterName