Apex programming Examples

Apex programming Examples

On January 6, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Apex programming Examples

Here we will use the Developer Edition Environment of salesforce and In this example, we will discuss object and field creation in Salesforce and how to use them in code for implementing business logic.

You can read Salesforce Apex Tutorial – Chapter 2: Apex Environment and the next article Salesforce Apex Tutorial – Chapter 4: Data Types In Apex.

Apex Trigger for Account

An Apex Trigger for Account is a custom script written in Salesforce’s Apex programming language, designed to execute automated actions before or after certain events occur on Account records in Salesforce. These events can include creating a new account, updating an existing account, or deleting an account. The trigger essentially listens for specific changes or actions performed on Account objects and then executes predefined logic, allowing for complex business processes to be automated directly within the Salesforce platform.

For example, an Apex Trigger could be configured to automatically update related records, enforce data validation rules, or even integrate with external systems when an Account record is modified. This level of customization makes Apex Triggers a powerful tool for tailoring Salesforce’s standard Account functionality to meet unique business requirements, ensuring data integrity, and enhancing overall system efficiency.

This trigger automatically updates a custom field NumberOfContacts on the Account object whenever a new contact is added or an existing one is deleted.

trigger UpdateContactCount on Contact (after insert, after delete) {
    Set<Id> accountIds = new Set<Id>();
    
    if (Trigger.isInsert) {
        for (Contact c : Trigger.new) {
            accountIds.add(c.AccountId);
        }
    }
    if (Trigger.isDelete) {
        for (Contact c : Trigger.old) {
            accountIds.add(c.AccountId);
        }
    }

    List<Account> accountsToUpdate = [SELECT Id, NumberOfContacts__c 
                                      FROM Account 
                                      WHERE Id IN :accountIds];
    for (Account a : accountsToUpdate) {
        a.NumberOfContacts__c = [SELECT count() 
                                 FROM Contact 
                                 WHERE AccountId = a.Id];
    }

    update accountsToUpdate;
}

Apex Class for Opportunity Management

An Apex Class for Opportunity Management is a structured collection of code that encapsulates specific functions or logic related to managing Opportunity records in Salesforce. This custom class can define methods to automate complex business processes, manipulate data, or integrate with external systems, all centered around the Opportunity object. By creating methods within this class, developers can perform operations like updating opportunity stages, calculating discounts, or aggregating data across related records, directly aligning with business workflows.

Utilizing an Apex Class for Opportunity Management allows for a more organized and modular approach to handling business logic in Salesforce. It not only enhances code maintainability but also allows for reusability and clearer separation of concerns. For instance, a method within this class can be invoked by triggers, batch jobs, or even from the Salesforce UI through Visualforce or Lightning Components, making it a versatile and integral part of the Salesforce development ecosystem.

This class includes a method that closes all open opportunities related to an account as ‘Lost’.

public class OpportunityManager {
    public static void closeOpportunitiesAsLost(String accountId) {
        List<Opportunity> opportunities = [SELECT Id, StageName 
                                           FROM Opportunity 
                                           WHERE AccountId = :accountId 
                                           AND IsClosed = false];

        for (Opportunity opp : opportunities) {
            opp.StageName = 'Closed Lost';
        }

        update opportunities;
    }
}

Batch Apex for Data Cleanup

Batch Apex for Data Cleanup is a specialized use of Salesforce’s Batch Apex, a powerful tool designed to handle large data sets by processing records in small batches. Specifically tailored for data maintenance tasks, Batch Apex for Data Cleanup allows developers to define complex and resource-intensive operations that identify, process, and delete outdated or irrelevant records from the Salesforce database. This is particularly useful for maintaining data quality and adhering to storage limits, especially in large-scale Salesforce environments where data accumulates rapidly.

With Batch Apex for Data Cleanup, the job is divided into manageable chunks, ensuring that the operations do not exceed Salesforce’s governor limits, which are in place to optimize performance and resource usage. The process involves querying the necessary records, performing the cleanup operation (like deleting or archiving), and then iterating over the batches until all the targeted data is processed. This method is not only efficient but also offers the ability to schedule cleanup operations, monitor job progress, and handle exceptions gracefully, making it an essential tool for maintaining a clean and efficient Salesforce instance.

This batch class finds and deletes old records from a custom object MyCustomObject__c .

public class OpportunityManager {
    public static void closeOpportunitiesAsLost(String accountId) {
        List<Opportunity> opportunities = [SELECT Id, StageName 
                                           FROM Opportunity 
                                           WHERE AccountId = :accountId 
                                           AND IsClosed = false];

        for (Opportunity opp : opportunities) {
            opp.StageName = 'Closed Lost';
        }

        update opportunities;
    }
}

Test Class for Apex Method

A Test Class for Apex Method in Salesforce is a framework for ensuring that your Apex code behaves as expected and adheres to the platform’s quality standards. It’s a collection of test methods specifically written to verify the logic of your Apex code by invoking the methods in your classes and checking that the outcomes are as anticipated. These test classes are essential for identifying any issues or bugs before the code is deployed to production. They also play a crucial role in fulfilling Salesforce’s code coverage requirement, which mandates that a certain percentage of your Apex code must be covered by tests to ensure robustness and reliability.

Writing a Test Class involves creating scenarios to test each unit of functionality in your Apex code, simulating different conditions, and asserting that the code responds correctly. This not only includes testing for expected outcomes but also handling unexpected or edge cases, ensuring that your application is stable and behaves consistently under various circumstances. Test classes in Salesforce are isolated from your actual data and configurations, meaning they allow for safe testing without affecting your live data. This isolation emphasizes the importance of preparing test data within your test classes to ensure your tests are comprehensive and reliable.

This is a test class for a simple Apex method that adds two numbers. It’s crucial to write test classes to ensure your Apex code works as expected and to meet Salesforce’s code coverage requirements.

@isTest
private class MathTest {
    static testMethod void testAddTwoNumbers() {
        Integer sum = MathClass.addNumbers(5, 3);
        System.assertEquals(8, sum, 'The sum of 5 and 3 should be 8');
    }
}

public class MathClass {
    public static Integer addNumbers(Integer a, Integer b) {
        return a + b;
    }
}

Top 5 Multiple Choice Questions for Salesforce Apex Examples

  1. What is the primary purpose of an Apex Trigger in Salesforce?
    • A) To generate reports and dashboards
    • B) To automatically perform an action before or after data manipulation
    • C) To customize the Salesforce UI
    • D) To integrate Salesforce with external systems
  2. In a Batch Apex class for data cleanup, what is the purpose of the ‘start’ method?
    • A) To define the batch size
    • B) To execute the batch job
    • C) To specify the records to be processed by the batch job
    • D) To summarize the results of the batch job
  3. Which statement about test classes in Apex is true?
    • A) Test classes are optional and not necessary for deployment.
    • B) Test classes can modify data in your production org.
    • C) Test classes help verify the logic of your Apex code and are required to meet code coverage.
    • D) Test classes are used to change user permissions and profiles.
  4. In Apex, what is the purpose of using the ‘Database.QueryLocator’ in a batch Apex class?
    • A) To update records in the database
    • B) To locate and fix database errors
    • C) To efficiently process large sets of records by dividing them into smaller batches
    • D) To locate a specific record in the database without using SOQL
  5. What is the result of using the ‘delete’ DML statement in a Batch Apex class for data cleanup?
    • A) It creates a backup of the records before deleting.
    • B) It permanently removes the specified records from the database.
    • C) It marks the records as deleted, but they can be restored from the Recycle Bin.
    • D) It flags the records for review before the actual deletion.

Answers:
1. B
2. C
3. C
4. C
5. B

Comments are closed.