Apex Programming Class and Coding Examples

What is Apex in Salesforce?

Apex is a programming language to develop custom applications on the Salesforce platform. It is similar to Java and has a syntax that is easy to learn for developers familiar with object-oriented programming.

With Apex, developers can create custom business logic and perform complex operations on data within the Salesforce platform. Apex code runs on the Salesforce servers and is highly secure and scalable. It can be used to automate business processes, integrate with external systems, and build custom user interfaces.

Apex can be used to create triggers, which are pieces of code that run automatically in response to certain events, such as when a record is created, updated, or deleted. It can also be used to create custom controllers, which control the behavior of custom user interfaces and create custom classes, which are reusable pieces of code that can be used across multiple applications.

Features of Apex Programming Language

Apex is a powerful programming language for developing custom applications on the Salesforce platform. Here are some of its key features:

  1. Highly Secure: Apex code runs on the Salesforce servers, which provides a high level of security. Salesforce also provides built-in security features, such as sharing rules, that can control data access.
  2. Web Services: Apex can be used to create web services that external systems can access. This allows for easy integration with third-party systems and applications.
  3. Batch Processing: Apex provides a batch processing feature that allows the processing of large amounts of data in batches. This can be used for tasks such as data cleanup and migration.
  4. Object-Oriented: Apex is an object-oriented programming language that uses classes and objects to create reusable code that can be easily maintained and updated.
  5. Integration with Salesforce Platform: Apex is integrated with the Salesforce platform, which means it can interact with Salesforce data and metadata. This makes it easy to build custom applications that work seamlessly with the Salesforce platform.
  6. Triggers: Apex can be used to create triggers, which are pieces of code that run automatically in response to certain events, such as when a record is created, updated, or deleted. This allows for easy automation of business processes.
  7. Test Framework: Apex provides a built-in test framework that allows developers to write unit tests for their code. This helps ensure that code is functioning correctly and can be easily maintained.

When Should Developer Choose Apex

Developers should choose Apex when building custom applications on the Salesforce platform. Since Salesforce is a cloud-based CRM platform, it provides a wide range of functionalities and features out-of-the-box, which can be customized using declarative tools such as Workflow Rules, Process Builder, and Flows.

Some scenarios where developers might choose to use Apex include:

  1. When complex business logic needs to be implemented, such as complex validation rules, conditional logic, or calculations.
  2. When custom integrations need to be built with external systems or applications.
  3. When batch processing needs to be performed on large amounts of data.
  4. When multiple objects must be updated in a single transaction, or data must be transformed or cleaned up.
  5. When custom user interfaces need to be built, such as custom pages or components that are not available through the declarative tools.

Working Structure of Apex

Here are the key elements of the operational structure of Apex:

  1. Objects: In Apex, objects are instances of classes representing data in the Salesforce platform. Objects can be standard objects (such as accounts and contacts) or custom objects (defined by the developer).
  2. Methods: Apex supports a variety of methods, including constructors, getters and setters, and action methods. Methods can be used to perform calculations, manipulate data, and perform other tasks.
  3. Governor Limits: Apex has a set of governor limits that restrict the number of resources a piece of code can use. These limits are in place to ensure the stability and performance of the Salesforce platform.
  4. Classes: Apex is built around classes, which are collections of variables and methods that define the behavior of objects. Classes can be used to define custom objects, controllers, and other components.
  5. Variables: Apex supports various data types, including primitives (integers and booleans) and objects. Variables can be declared and initialized using standard syntax.
  6. Triggers: Apex triggers are pieces of code executed automatically in response to events in the Salesforce platform, such as creating or updating a record.
  7. Debugging and Testing: Apex provides various tools for debugging and testing code, including logs, the Apex Debugger, and the Apex Test Framework.

Apex Syntax

1. Variable Declaration:

Variable declaration is creating a variable in a program and specifying its data type and name. In Apex, variables are declared using the syntax:

where data_type is the variable's data type, and variable_name is the variable's name.

Apex supports a variety of data types, including:

  • Primitive data types: Integer, Long, Double, Decimal, Boolean, Date, Datetime, and String.
  • Collections: List, Set, and Map.
  • SObject data types: Any standard or custom object.

2. SOQL Query:

In Apex, SOQL queries can be executed using the Database. query() method or using SOQL query strings directly in your code. The basic syntax for writing a SOQL query in Apex is as follows:

where SObject is the name of the object being queried, field1, field2, etc., are the fields to retrieve, and the condition is an optional expression that filters the results.

Additionally, Apex supports several other features in SOQL queries, such as:

  • Aggregate functions: COUNT(), SUM(), AVG(), MIN(), MAX()
  • Relationship queries: SELECT field1, field2, ... FROM parentObject WHERE Id IN (SELECT parentId FROM childObject WHERE condition)
  • Order By: ORDER BY field ASC|DESC
  • Group By: GROUP BY field1, field2
  • Limit: LIMIT n
  • Offset: OFFSET n

3. Loop Statement:

In Apex, loop statements are used to execute a block of code repeatedly until a certain condition is met. There are four types of loop statements in Apex:

  1. for loop: A for loop is used to iterate over a list, set, or map of elements. The syntax for a for loop is:
  1. while loop: A while loop executes a block of code repeatedly as long as a certain condition is true. The syntax for a while loop is:
  1. do-while loop: A do-while loop is similar to a while loop, except the code block is executed at least once before checking the condition. The syntax for a do-while loop is:
  1. foreach loop: A foreach loop is used to iterate over a list of SObject records returned by a SOQL query. The syntax for a foreach loop is:

4. Flow Control Statement:

In Apex, flow control statements are used to control the execution flow of the program. There are three types of flow control statements in Apex:

i. Conditional statements:

Conditional statements are used to execute different blocks of code based on the value of a certain condition. There are two types of conditional statements in Apex:

  • If statement: The if statement executes a block of code if a certain condition is true. The syntax for an if statement is:
  • If-else statement: The if-else statement executes a block of code if a certain condition is true and another block of code if the condition is false. The syntax for an if-else statement is:

ii. Loop statements:

Loop statements are used to execute a block of code repeatedly until a certain condition is met. There are four types of loop statements in Apex:

  • for loop: The for loop is used to iterate over a list, set, or map of elements.
  • while loop: The while loop is used to execute a block of code repeatedly as long as a certain condition is true.
  • do-while loop: The do-while loop is similar to the while loop, except that the code block is executed at least once before checking the condition.
  • foreach loop: The foreach loop is used to iterate over a list of SObject records returned by a SOQL query.

iii. Transfer statements

Transfer statements are used to transfer control to another part of the program. There are three types of transfer statements in Apex:

  • Break statement: The break statement is used to exit a loop prematurely.
  • Continue statement: The continue statement is used to skip the current iteration of a loop and continue with the next one.
  • Return statement: The return statement is used to exit a method prematurely and return a value to the calling code.

iv. DML statement:

DML (Data Manipulation Language) statements in Apex are used to manipulate data in the Database. Apex supports several DML statements, including:

  • Insert: The insert statement is used to insert new records into the Database.
  • Update: The update statement is used to update existing records in the Database.
  • Delete: The delete statement is used to delete existing records from the Database.
  • Upsert: The upsert statement is used to insert or update records in the Database based on a specified external ID field.
  • Undelete: The undelete statement is used to recover deleted records from the Recycle Bin.

Apex String

In Apex, a string is a sequence of characters enclosed in single or double quotes. Strings are used to store and manipulate text data.

Here are some examples of string variables in Apex:

The String class provides several in-built methods in Salesforce. Following are the few frequently and mostly used functions:

1. maxWidth:

"maxWidth" generally refers to the maximum width or length a string can be before it is truncated or abbreviated.

Example

Output:-

Apex Programming Class & Coding Examples

2. capitalize():

In Apex, the capitalize() method is a standard string method that is used to capitalize the first character of a string. This method does not modify the original string and returns a new string with the first character capitalized.

Here is an example of how to use the capitalize() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'hello, world!'. We then use the capitalize() method to create a new string called capitalizedString with the first character capitalized. Finally, we output the value of capitalizedString to the debug log, which should print 'Hello, world!'.

3. contains(substring):

In Apex, the contains() method is a standard string method that is used to check if a string contains a specified substring. The method returns a Boolean value indicating whether or not the substring is found in the string.

Here's an example of how to use the contains() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'The quick brown fox jumps over the lazy dog'. We then use the contains() method to check if the string contains the substring 'brown', and assign the result to a Boolean variable called containsSubstring. Finally, we output the value of containsSubstring to the debug log, which should print true, indicating that the string does indeed contain the substring 'brown'.

4. equals(stringOrId):

In Apex, the equals() method is a standard method that is used to compare a string to another string or an ID value. The method returns a Boolean value indicating whether or not the two values are equal.

Here's an example of how to use the equals() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'hello'. We then use the equals() method to compare the value of myString to the string 'hello', and assign the result to a Boolean variable called stringEquals. Finally, we output the value of stringEquals to the debug log, which should print true, indicating that the two strings are equal.

5. escapeSingleQuotes(stringToEscape):

In Apex, the escapeSingleQuotes() method is a standard method that is used to escape single quotes in a string. This method replaces every single quote character (') in the string with two single quotes (''). This is often used to safely include single quotes in a SOQL query or other string that is enclosed in single quotes.

Here's an example of how to use the escapeSingleQuotes() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'She said, "I don't like pizza"'. Note that the string contains a single quote within the double quotes, which could cause problems if the string is used in a SOQL query or other context where the string is enclosed in single quotes. We then use the escapeSingleQuotes() method to replace the single quote with two single quotes and assign the result to a new string variable called escapedString. Finally, we output the value of escapedString to the debug log, which should print 'She said, "I don't like pizza,"' with the single quote properly escaped.

6. remove(substring):

In Apex, the remove() method is a standard string method that is used to remove all occurrences of a specified substring from a string. The method returns a new string with the specified substring removed.

Here's an example of how to use the remove() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'The quick brown fox jumps over the lazy dog'. We then use the remove() method to remove the substring 'brown' from the string and assign the result to a new string variable called removedString. Finally, we output the value of removedString to the debug log, which should print 'The quick fox jumps over the lazy dog', with the substring 'brown' removed.

7. substring(startIndex):

In Apex, the substring() method is a standard method used to extract a portion of a string, starting at a specified index and continuing to the end. The method returns a new string that contains the specified portion of the original string.

Here's an example of how to use the substring() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'The quick brown fox jumps over the lazy dog'. We then use the substring() method to extract a portion of the string starting at index 10 (corresponding to the letter 'b' in the word 'brown') and assign the result to a new string variable called subString. Finally, we output the value of subString to the debug log, which should print 'brown fox jumps over the lazy dog', the portion of the original string starting at index ten and continuing to the end of the string.

8. reverse():

In Apex, the reverse() method is a standard method that is used to reverse the order of characters in a string. The method returns a new string with the characters in reverse order.

Here's an example of how to use the reverse() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare a string variable called myString and assign it the value 'The quick brown fox'. We then use the reverse() method to reverse the order of characters in the string and assign the result to a new string variable called reversedString. Finally, we output the value of reversedString to the debug log, which should print 'xof nworb kciuq ehT,' the original string with the characters in reverse order.

9. valueOf(toConvert):

In Apex, the valueOf() method is a standard method used to convert various data types to a string representation. The method takes a single parameter, the value to be converted, and returns a string representation of that value.

Here's an example of how to use the valueOf() method in Apex:

Output:

Apex Programming Class & Coding Examples

In this example, we declare an integer variable called myInt and assign it the value 42. We then use the valueOf() method to convert the integer value to a string representation and assign the result to a new string variable called myString. Finally, we output the value of myString to the debug log, which should print '42', the string representation of the original integer value.

Apex Class

In Apex, a class is a blueprint for creating objects that define the behavior and properties of those objects. A class contains variables, methods, constructors, and other features that define the behavior of the objects created from the class.

For example,

Output:

Apex Programming Class & Coding Examples

In this example, we have defined a class called MyClass with two variables (myString and myInt), a constructor that sets the values of those variables, and a method (myMethod) that outputs the values of the variables to the debug log.

Apex Trigger

In Apex, a trigger is a piece of code that executes before or after specific data manipulation events occur in Salesforce, such as inserting, updating, deleting, or undeleting records. Triggers can be used to automate business processes, enforce data validation rules, and perform custom calculations or other actions.

Here's an example of a simple Apex trigger:

Output:

NO OUTPUT

In this example, we have defined a trigger called CreateContact that runs after a new Account record is inserted. The trigger creates a new list of Contact records and populates them with some default values, including the Account Id of the new Account record. Finally, the trigger inserts the new Contact records into the Database.






Latest Courses