Tag Archives: Apex

An Introduction to Apex class

index

Apex is a strongly-typed Object-Oriented Programming (OOP) language that executes on the Force.com platform. Apex is used to add business logic to applications, to write database triggers, and to program controllers in the user interface layer. It has a tight integration with the database and query language, good web services support, and includes features such as futures and governors for execution in a multi-tenant environment.

Apex Class:

  • A class is a template or blueprint from which objects are created.
  • It consist of methods and attributes.
  • It stored with the version of API that is used to compile it.
  • It may contain other classes, known as inner classes (but these can only be one level deep).
  • Even though Apex code is not case sensitive, it is recommended that to follow the Java naming convention.
  • Static methods and attributes can only be declared in a top-level class definition.
  • Apex classes can be enabled or disabled for profiles and can only be 100,000 characters in length.
  • When a class is defined it becomes a new data type in Apex.

Apex Class Syntax:

private | public | global 
[virtual | abstract | with sharing | without sharing | (none)] 
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)] 
{ 
     // The body of the class
}

Apex allows to use the private, protected, public, and global access modifiers when defining classes, methods and variables. By default, a method or variable is visible only to the Apex code within the defining class. We must explicitly specify a method or variable as public in order for it to be available to other classes in the same application namespace. We can change the level of visibility by using the following access modifiers:

private – This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If we do not specify an access modifier, the method or variable is private.

protected – This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class. We can only use this access modifier for instance methods and member variables.

public – This means the method or variable can be used by any Apex in this application or namespace.

global – This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If we declare a method or variable as global, we must also declare the class that contains it as global.

with sharing or without sharing:

  • We use the with sharing or without sharing keywords on a class to specify whether or not to enforce sharing rules.
  • The with sharing keyword allows to specify that the sharing rules for the current user be taken into account for a class.
  • We use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced.
  • If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect, this means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class.
  • Both inner classes and outer classes can be declared as with sharing.
  • The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods.
  • Inner classes do not inherit the sharing setting from their container class.
  • Classes inherit this setting from a parent class when one class extends or implements another.

virtual – The virtual definition modifier declares that this class allows extension and overrides. We cannot override a method with the override keyword unless the class has been defined as virtual. We cannot override a public or protected virtual method of a global class of an installed managed package.

Example of SubClass with Method Override:

public virtual class myParentClass {
 
 public myParentClass{
  //Constructor
 }
  
 public virtual void doSomething(){
  System.Debug('Do something'); 
 }
}
//Extension for the myParentClass class
public class myClass extends myParentClass{
 
 public myClass{
  //Constructor
 }
 
 public override void doSomething(){
   System.Debug('Do something else');
 } 
}

abstract – The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined. Abstract class methods MUST be overridden. We cannot add an abstract method to a global class after the class has been uploaded in a Managed – Released package version. If the class in the Managed – Released package is virtual, the method that we can add to it must also be virtual and must have an implementation.

Example of Abstract class with abstract method and Override:

public abstract class myParentClass{
 
 public myParentClass{
  //Constructor
 }
  
 public virtual void doSomething(){
  System.Debug('Do something'); 
 }
 
 //Abstract method without body
 public abstract void myAbstractMethod();
}
//Extension for the myParentClass abstract class
public class myClass extends myParentClass{
 
 public myClass{
  //Constructor
 }
 
 public override void doSomething(){
   System.Debug('Do something else');
 }
 
 public override void myAbstractMethod(){
   System.Debug('Do something');
 } 
}

Interface – An interface is like a class in which none of the methods have been implemented, the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

Example of Interface and its implementation on class:

public interface myInterface{
 
 public void doSomething();
}
//This class implements the myInterface interface.
public class myClass implements myInterface{
 
 public myClass{
  //Constructor
 }
 
 public void doSomething(){
   System.Debug('Do something else');
 }
}

Difference between List, Set and Map in Salesforce

List:

  • List is a collection of elements, Such as primitive data types (String, Integer, Date, etc), user defined objects, sObjects, Apex objects or other collections (can be multidimensional up to 5 levels).
  • List allows duplicate values.
  • List index position starts from zero.

Set:

  • Set is a collection of unique, unordered elements.
  • It can contain primitive data types (String, Integer, Date, etc) or sObjects.
  • Set allows unique values.

Map:

  • Map is a collection of key-value pair.
  • Keys can be any primitive data types (String, Integer, Date, etc) while values can include primitives, Apex objects, sObjects and other collections.
  • Map allows duplicate values, but each key must be unique.

Validation rule in apex trigger

Salesforce provides validation rules in configuration for standard and custom objects. sometimes the requirements may not be fulfilled using validation rule, especially when the validation criteria is very complex or need querying in database to check previously created data. In such a case we can write validation logic in trigger.

In this article, I will demonstrate how to write validation logic in apex trigger.

Here in below example, there is before insert and before update trigger on Opportunity object. In this trigger the amount field has validated, for less than 5000.

trigger TriggerOpportunity on Opportunity (before insert, before update){
    for(Opportunity opp:trigger.new){
        if(opp.Amount < 5000){
            opp.Amount.adderror('Amount cannot be less than 5000.');
        }
    }
}

download

Convert 15 digit Id to 18 digit Id in Salesforce apex class

In Salesforce each record Id represents a unique record within an Organisation.
These ids are in two formats for every record Id in Salesforce:

  • 15 digit case-sensitive version which is referenced in the UI (Detail pages / reports)
  • 18 digit case-insensitive version which is referenced through the API

Apex Class:

public class TestPage
{
    public String FifteenDigit {get;set;}
    public Id EighteenDigit {get;set;}
     
    public TestPage(){
        FifteenDigit = 'a0390000009ooJG';
        EighteenDigit = FifteenDigit;
    }
}

Visualforce Page:

<apex:page controller="TestPage" doctype="html-5.0">
   <apex:form>
       <apex:outputtext value="Fifteen Digit : "></apex:outputtext>
       <apex:outputtext value="{!FifteenDigit}"></apex:outputtext>
       <apex:outputtext value="Eighteen Digit : "></apex:outputtext>
       <apex:outputtext value="{!EighteenDigit}"></apex:outputtext>
   </apex:form>
</apex:page>

download

Note: CASESAFEID(Id) function in a formula field can be used to capture the 18 digit id of a record.

Apex Message in Visualforce Pages

Apex Messages in Salesforce are used for displaying messages such as a warning or an error in visualforce page. In this article I’ll demonstrate how to use different types of messaging options in VisualForce page.
Apex message severities are:

  • CONFIRM
  • ERROR
  • FATAL
  • INFO
  • WARNING

CONFIRM:

Visualforce Page:

<apex:page controller="SuccessMessage"> 
<apex:pagemessages> 
</apex:pagemessages> 
</apex:page> 

Apex Class:

public class SuccessMessage
{ 
   public SuccessMessage()
   {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Confirm, 'This is a success message'));
   }
} 

Confirm

 

ERROR:

Visulaforce Page:

<apex:page controller="ErrorMessages"> 
<apex:pagemessages> 
</apex:pagemessages> 
</apex:page> 

Apex Class:

public class ErrorMessages
{ 
   public ErrorMessages()
   {
     ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error, 'This is an error message'));
   }
}

Error

 

WARNING:

Visualforce Page:

<apex:page controller="WarningMessage"> 
<apex:pagemessages> 
</apex:pagemessages> 
</apex:page>

Apex Class:

public class WarningMessage
{ 
   public WarningMessage()
   {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Warning, 'This is a warning message'));
   }
} 

Warning

 

INFO:

Visualforce Page:

<apex:page controller="InfoMessage"> 
<apex:pagemessages> 
</apex:pagemessages> 
</apex:page>

Apex Class:

public class InfoMessage
{ 
   public InfoMessage()
   {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Info, 'This is an informational message'));
   }
}

Info