Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
Practical Paper
Industrial Training
Apex - overview
What is Apex?
Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API.
It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition.
Features of Apex as a Language
Let us now discuss the features of Apex as a Language −Integrated
Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters.Java like syntax and easy to use
Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements.Strongly Integrated With Data
Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database.Strongly Typed
Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type.Multitenant Environment
Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages.Upgrades Automatically
Apex is upgraded as part of Salesforce releases. We don't have to upgrade it manually.Easy Testing
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient.When Should Developer Choose Apex?
Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration.Apex Applications
We can use Apex when we want to −
- Create Web services with integrating other systems.
- Create email services for email blast or email setup.
- Perform complex validation over multiple objects at the same time and also custom validation implementation.
- Create complex business processes that are not supported by existing workflow functionality or flows.
- Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records.
- Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire.
Working Structure of Apex
As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform.Flow of Actions
There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below −Developer Action
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata.End User Action
When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request.
Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support −
- It cannot show the elements in User Interface.
- You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution.
- Creating multiple threads is also not possible as we can do it in other languages.
Understanding the Apex Syntax
Apex code typically contains many things that we might be familiar with from other programming languages.Variable Declaration
As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts.SOQL Query
This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object.Loop Statement
This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have.Flow Control Statement
The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records.DML Statement
Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value.
Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial.
Apex - Environment
In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development. You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment. For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce.
Apex Code Development Tools
In all the editions, we can use any of the following three tools to develop the code − Force.com Developer Console Force.com IDE Code Editor in the Salesforce User Interface Note − We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning. Force.com Developer Console The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization.
Follow these steps to open the Developer Console −
Step 1 − Go to Name → Developer ConsoleStep 2 − Click on "Developer Console" and a window will appear as in the following screenshot.
Following are a few operations that can be performed using the Developer Console.
Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Testing − You can view debug logs and set checkpoints that aid in debugging.
Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage.
SOQL queries − You can inspect debug logs to locate performance bottlenecks.
Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names.
Executing Code in Developer Console
All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console.
Step 1 − Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code.
String myString = 'MyString';
System.debug('Value of String Variable'+myString);
Step 2 − To open the Developer Console, click on Name → Developer Console and then click on Execute Anonymous as shown below.
Step 3 − In this step, a window will appear and you can paste the code there. Executing Code in Developer Console step3.
Step 4 − When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record.
Then type 'USER' in the window as shown below and the output statement will appear in the debug window. This 'USER' statement is used for filtering the output. Executing Code in Developer Console Step4
So basically, you will be following all the above mentioned steps to execute any code snippet in this tutorial.
Apex - Example
Enterprise Application Development Example
For our tutorial, we will be implementing the CRM application for a Chemical Equipment and Processing Company. This company deals with suppliers and provides services. We will work out small code snippets related to this example throughout our tutorial to understand every concept in detail.
For executing the code in this tutorial, you will need to have two objects created: Customer and Invoice objects. If you already know how to create these objects in Salesforce, you can skip the steps given below. Else, you can follow the step by step guide below.
Creating Customer Object
We will be setting up the Customer object first.
Step 1 − Go to Setup and then search for 'Object' as shown below. Then click on the Objects link as shown below.
Step 2 − Once the object page is opened, then click on the 'Create New Object' button as shown below.
Step 3 − After clicking on button, the new object creation page will appear and then enter all the object details as entered below. Object name should be Customer. You just have to enter the information in the field as shown in the screenshot below and keep other default things as it is.
Enter the information and then click on the 'Save' button − Customer Object Ceation Step5
By following the above steps, we have successfully created the Customer object.
Creating the Custom Fields for Customer object
Now that we have our Customer object set up, we will create a field 'Active' and then you can create the other fields by following similar steps. The Name and API name of the field will be given in the screenshot.
Step 1 − We will be creating a field named as 'Active' of data type as Checkbox. Go to Setup and click on it.
Step 2 − Search for 'Object' as shown below and click on it.
Step 3 − Click on object 'Customer'.
Step 4 − Once you have clicked on the Customer object link and the object detail page appears, click on the New button. Customer Custom Field Creation Step4
Step 5− Now, select the data type as Checkbox and click Next. Customer Custom Field Creation Step5
Step 6 − Enter the field name and label as shown below.
Step 7 − Click on Visible and then click Next.
Step 8 − Now click on 'Save'.
By following the above steps, our custom field 'Active' is created. You have to follow all the above custom field creation steps for the remaining fields. This is the final view of customer object once all the fields are created − Final View Customer Object
Creating Invoice Object
Step 1 − Go to Setup and search for 'Object' and then click on the Objects link as shown below.
Step 2− Once the object page is opened, then click on the 'Create New Object' button as shown below.
Step 3 − After clicking on the button, the new object creation page will appear as shown in the screenshot below. You need to enter the details here. The object name should be Invoice. This is similar to how we created the Customer object earlier in this tutorial.
Step 4 − Enter the information as shown below and then click on the 'Save' button. Invoice Object Creation
By following these steps, your Invoice object will be created.
Creating the Custom Fields for Invoice object
We will be creating the field Description on Invoice object as shown below −
Step 1 − Go to Setup and click on it.
Step 2 − Search for 'Object' as shown below and click on it.
Step 3 − Click on object 'Invoice'.
And then click on 'New'.
Step 4 − Select the data type as Text Area and then click on Next button.
Step 5 − Enter the information as given below.
Step 6 − Click on Visible and then Next.
Step 7 − Click on Save.
Similarly, you can create the other fields on the Invoice object.
By this, we have created the objects that are needed for this tutorial. We will be learning various examples in the subsequent chapters based on these objects.
Apex - Data Types
Understanding the Data Types
The Apex language is strongly typed so every variable in Apex will be declared with the specific data type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper values are assigned to the variables. Otherwise such variables when used, will throw null pointer exceptions or any unhandled exceptions.
Apex supports the following data types −
1.Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean)
2.Collections (Lists, Sets and Maps) (To be covered in Chapter 6)
3.sObject
4.Enums
5.Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13)
In this chapter, we will look at all the Primitive Data Types, sObjects and Enums. We will be looking at Collections, Classes, Objects and Interfaces in upcoming chapters since they are key topics to be learnt individually.
Primitive Data Types
In this section, we will discuss the Primitive Data Types supported by Apex.
Integer
A 32-bit number that does not include any decimal point. The value range for this starts from -2,147,483,648 and the maximum value is up to 2,147,483,647.
Example
We want to declare a variable which will store the quantity of barrels which need to be shipped to the buyer of the chemical processing plant.
Integer barrelNumbers = 1000;
system.debug(' value of barrelNumbers variable: '+barrelNumbers);
The System.debug() function prints the value of variable so that we can use this to debug or to get to know what value the variable holds currently. Paste the above code to the Developer console and click on Execute. Once the logs are generated, then it will show the value of variable "barrelNumbers" as 1000.
Boolean
This variable can either be true, false or null. Many times, this type of variable can be used as flag in programming to identify if the particular condition is set or not set.
Example
If the Boolean shipmentDispatched is to be set as true, then it can be declared as −
Boolean shipmentDispatched;
shipmentDispatched = true;
System.debug('Value of shipmentDispatched '+shipmentDispatched);
Date
This variable type indicates a date. This can only store the date and not the time. For saving the date along with time, we will need to store it in variable of DateTime.
Example
Consider the following example to understand how the Date variable works.
//ShipmentDate can be stored when shipment is dispatched.
Date ShipmentDate = date.today();
System.debug('ShipmentDate '+ShipmentDate);
Long
This is a 64-bit number without a decimal point. This is used when we need a range of values wider than those provided by Integer.
ExampleIf the company revenue is to be stored, then we will use the data type as Long.
Long companyRevenue = 21474838973344648L;
system.debug('companyRevenue'+companyRevenue);
Object
We can refer this as any data type which is supported in Apex. For example, Class variable can be object of that class, and the sObject generic type is also an object and similarly specific object type like Account is also an Object.
Example
Consider the following example to understand how the bject variable works.
Account objAccount = new Account (Name = 'Test Chemical');
system.debug('Account value'+objAccount);
Note − You can create an object of predefined class as well, as given below −
//Class Name: MyApexClass
MyApexClass classObj = new MyApexClass();
This is the class object which will be used as class variable.
String
String is any set of characters within single quotes. It does not have any limit for the number of characters. Here, the heap size will be used to determine the number of characters. This puts a curb on the monopoly of resources by the Apex program and also ensures that it does not get too large.
Example
String companyName = 'Abc International';
System.debug('Value companyName variable'+companyName);
Time
This variable is used to store the particular time. This variable should always be declared with the system static method.
Blob
The Blob is a collection of Binary data which is stored as object. This will be used when we want to store the attachment in salesforce into a variable. This data type converts the attachments into a single object. If the blob is to be converted into a string, then we can make use of the toString and the valueOf methods for the same.
sObject
This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL. There are two types of sObjects – Standard and Custom.
For example, Account is a standard sObject and any other user-defined object (like Customer object that we created) is a Custom sObject.
Example
//Declaring an sObject variable of type Account
Account objAccount = new Account();
//Assignment of values to fields of sObjects
objAccount.Name = 'ABC Customer';
objAccount.Description = 'Test Account';
System.debug('objAccount variable value'+objAccount);
//Declaring an sObject for custom object APEX_Invoice_c
APEX_Customer_c objCustomer = new APEX_Customer_c();
//Assigning value to fields
objCustomer.APEX_Customer_Decscription_c = 'Test Customer';
System.debug('value objCustomer'+objCustomer);
Enum
Enum is an abstract data type that stores one value of a finite set of specified identifiers. You can use the keyword Enum to define an Enum. Enum can be used as any other data type in Salesforce.
Example
You can declare the possible names of Chemical Compound by executing the following code −
//Declaring enum for Chemical Compounds
public enum Compounds {HCL, H2SO4, NACL, HG}
Compounds objC = Compounds.HCL;
System.debug('objC value: '+objC);
Apex - Variables
Java and Apex are similar in a lot of ways. Variable declaration in Java and Apex is also quite the same. We will discuss a few examples to understand how to declare local variables.
String productName = 'HCL';
Integer i = 0;
Set
Map
Note that all the variables are assigned with the value null.
Declaring Variables
You can declare the variables in Apex like String and Integer as follows −
String strName = 'My String'; //String variable declaration
Integer myInteger = 1; //Integer variable declaration
Boolean mtBoolean = true; //Boolean variable declaration
Apex variables are Case-Insensitive
This means that the code given below will throw an error since the variable 'm' has been declared two times and both will be treated as the same.
Integer m = 100;
for (Integer i = 0; i<10; i++) {
integer m = 1; //This statement will throw an error as m is being declared
again
System.debug('This code will throw error');
}
Scope of Variables
An Apex variable is valid from the point where it is declared in code. So it is not allowed to redefine the same variable again and in code block. Also, if you declare any variable in a method, then that variable scope will be limited to that particular method only. However, class variables can be accessed throughout the class.
Example
//Declare variable Products
List
Products.add('HCL');
//You cannot declare this variable in this code clock or sub code block again
//If you do so then it will throw the error as the previous variable in scope
//Below statement will throw error if declared in same code block
List