Study to Apex Classes in Salesforce and Key Components for Custom Logic and Automation

An Apex class in Salesforce is a blueprint used to define the behaviors and characteristics of an object. Apex is Salesforce’s proprietary programming language, and an Apex class encapsulates the code that enables developers to create custom solutions, automate tasks, and extend the functionality of Salesforce’s standard offerings. It is structured in a similar way to Java, allowing for object-oriented programming and code reuse.

Apex Classes In Salesforce

Apex classes are utilized to build complex business logic, enabling developers to customize applications beyond standard point-and-click configurations. They support DML operations, SOQL queries, and even external web service callouts. By leveraging Apex classes, you can create custom workflows, batch processes, and triggers, and even manage integration with external systems. Apex classes are a vital part of the Salesforce platform, empowering developers to deliver highly tailored business solutions within the Salesforce ecosystem.

Apex Classes in Salesforce

Why Are Apex Classes Important in Salesforce?

Without Apex classes, Salesforce wouldn’t know how to handle more complex jobs. It’s like giving a robot the ability to think. Apex allows Salesforce to handle logic and business rules.

Apex Class Examples in Salesforce

Here’s an example of a simple Apex class that creates a new contact:

public class CreateContact {

    public void createNewContact() {

        Contact newContact = new Contact(FirstName = 'John', LastName = 'Doe', Email = 'john.doe@example.com');

        insert newContact;

    }

}

Basic Apex Class in Salesforce

This is a simple example of an Apex class that defines a method to display a greeting.

public class HelloWorld {

    public static String sayHello() {

        return 'Hello, Salesforce!';

    }

}

Apex Class with Parameters

This example takes a name as input and returns a personalized greeting.

public class Greeting {

    public static String greetUser(String name) {

        return 'Hello, ' + name + '!';

    }

}

Apex Class for Record Creation

This class creates a new Account record in Salesforce.

public class AccountCreator {

    public static void createAccount(String accName) {

        Account acc = new Account(Name = accName);

        insert acc;

    }

}

Apex Class for Updating Records

This example updates the phone number for a given Account.

public class UpdateAccount {

    public static void updatePhone(Id accId, String phone) {

        Account acc = [SELECT Id, Phone FROM Account WHERE Id = :accId];

        acc.Phone = phone;

        update acc;

    }

}

Apex Class with SOQL Query

This class fetches and returns a list of Account names.

public class AccountList {

    public static List<String> getAccountNames() {

        List<Account> accList = [SELECT Name FROM Account];

        List<String> accNames = new List<String>();

        for (Account acc : accList) {

            accNames.add(acc.Name);

        }

        return accNames;

    }

}

Apex Class to Call from a Button

This example demonstrates how to call an Apex class from a button in Salesforce.

public class ButtonCallClass {

    public static void buttonAction() {

        System.debug('Button clicked!');

    }

}

Batch Apex Class in Salesforce

This class processes large sets of records in batches.

Apex Test Class Example

global class BatchProcessAccounts implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {

        return Database.getQueryLocator('SELECT Id, Name FROM Account');

    }

    global void execute(Database.BatchableContext BC, List<Account> scope) {

        for (Account acc : scope) {

            acc.Phone = '1234567890';

        }

        update scope;

    }

    global void finish(Database.BatchableContext BC) {

        System.debug('Batch process completed!');

    }

}

A simple test class that tests the HelloWorld Apex class.

@isTest

public class HelloWorldTest {

    @isTest

    static void testSayHello() {

        String result = HelloWorld.sayHello();

        System.assertEquals('Hello, Salesforce!', result);

    }

}

Apex Class with Trigger

This example uses an Apex trigger to call an Apex class when an Account is inserted.

trigger AccountTrigger on Account (before insert) {

    AccountCreator.createAccount('Test Account');

}

Apex Class to Call Integration Procedure

This class demonstrates how to call an external integration procedure.

public class IntegrationExample {

    public static void callExternalAPI() {

        HttpRequest req = new HttpRequest();

        req.setEndpoint('https://example.com/api');

        req.setMethod('GET');

        Http http = new Http();

        HttpResponse res = http.send(req);

        System.debug(res.getBody());

    }

}

Apex Class with Flow Integration

This class can be invoked from a Flow in Salesforce.

public class FlowIntegration {

    @InvocableMethod

    public static void updateAccountNames(List<String> names) {

        for (String name : names) {

            Account acc = new Account(Name = name);

            insert acc;

        }

    }

}

Apex Class with Custom Exception

This class throws a custom exception when a condition is not met.

public class CustomExceptionExample {

    public static void validateAccount(Account acc) {

        if (acc.Name == null) {

            throw new CustomException('Account name is required');

        }

    }

    public class CustomException extends Exception {}

}

Apex Class for Querying Data

This class returns a list of all active Accounts.

Apex Class for Deleting Records

public class ActiveAccounts {

    public static List<Account> getActiveAccounts() {

        return [SELECT Id, Name FROM Account WHERE IsActive__c = true];

    }

}

This class deletes a given Account from Salesforce.

Apex Class for Code Coverage Check

public class AccountDeleter {

    public static void deleteAccount(Id accId) {

        Account acc = [SELECT Id FROM Account WHERE Id = :accId];

        delete acc;

    }

}

This class checks if a particular method is covered by tests.

Apex Class Methods in Salesforce

public class CodeCoverageCheck {

    public static Boolean isMethodCovered() {

        Test.startTest();

        String result = HelloWorld.sayHello();

        Test.stopTest();

        return (result == 'Hello, Salesforce!');

    }

}

A method in an Apex class is like a mini task inside the bigger job. It helps you break down the work into smaller pieces. For example, if you’re baking a cake, one method might be mixing ingredients, and another might be baking the cake.

Here’s an example of a method inside an Apex class:

public class Greeting {

    public String sayHello(String name) {

        return 'Hello, ' + name + '!';

    }

}

In this method, we’re creating a task that says hello to someone. If you give the method a name, like “Jack,” it will return “Hello, Jack!”

Difference Between Apex Classes and Triggers in Salesforce

An Apex class is a blueprint that tells Salesforce what to do, but it only works when you tell it to. A trigger, on the other hand, automatically runs when something happens in the system, like when a new record is created.

Think of it this way: an Apex class is like a remote-controlled car – you need to press a button to make it move. A trigger is like a motion sensor – it starts working automatically when something happens.

How to Create Apex Class in Salesforce

Creating an Apex class in Salesforce is easy! Just follow these steps:

  1. Log in to Salesforce and go to the Developer Console.
  2. Click File > New > Apex Class.
  3. Name your class and start writing your code!

Here’s how you can create a basic Apex class:

public class HelloWorld {

    public String sayHello() {

        return 'Hello, World!';

    }

}

This simple Apex class returns the message “Hello, World!”

Apex Test Classes in Salesforce

Before you can deploy your Apex class into production (the real working environment), you need to test it. Apex test classes make sure your code works as expected.

Here’s an example of a test class:

@isTest

public class HelloWorldTest {

    @isTest

    public static void testSayHello() {

        HelloWorld hw = new HelloWorld();

        String result = hw.sayHello();

        System.assertEquals('Hello, World!', result);

    }

}

This test class checks if the HelloWorld class works correctly by comparing the result to “Hello, World!”

Batch Apex Class in Salesforce

A batch Apex class is used to handle large sets of data. Imagine you have thousands of records to update – a batch job helps process them in smaller chunks, so your system doesn’t crash.

Here’s an example of a batch Apex class:

global class BatchExample implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {

        return Database.getQueryLocator('SELECT Id FROM Account');

    }

    global void execute(Database.BatchableContext BC, List<Account> scope) {

        for (Account acc : scope) {

            acc.Name = 'Updated Account';

        }

        update scope;

    }

    global void finish(Database.BatchableContext BC) {}

}

This batch Apex class updates all accounts in your system by changing their names to “Updated Account.”

Call Apex Class from a Button in Salesforce

You can even create buttons in Salesforce that run your Apex class. For example, you might want to create a button that runs the create contact function we talked about earlier.

Here’s how you can do it:

  1. Go to Setup in Salesforce.
  2. Find Buttons, Links, and Actions under your desired object.
  3. Create a new button and call the Apex class method through it.
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var result = sforce.apex.execute('CreateContact', 'createNewContact', {});

alert('New Contact Created!');

Default Sharing for Apex Class in Salesforce

When you create an Apex class, it’s important to consider sharing settings. By default, Apex respects the security model of Salesforce, but you can control access by using keywords like “with sharing” or “without sharing.”

public with sharing class ContactManager {

    // Your code here

}

How to Call Apex Class from Flow in Salesforce

Sometimes, you may want to trigger an Apex class using Salesforce Flow. You can do this by creating an Apex action in your flow.

  • In the Flow Builder, drag the Apex Action element.
  • Choose your Apex class from the list.
  • Set the parameters if needed.

How to Call Apex Class from JavaScript in Salesforce

You can also call Apex classes from JavaScript using Lightning Web Components or Visualforce pages. Here’s an example of how to call an Apex class from JavaScript:

import callApexMethod from ‘@salesforce/apex/YourApexClass.methodName’;

How to Debug Apex Class in Salesforce

Debugging is like figuring out why something isn’t working in your code. Salesforce provides tools like Debug Logs to help you understand what’s going wrong. You can use System.debug() in your Apex class to print messages.

public class DebugExample {

    public void doSomething() {

        System.debug('This is a debug message');

    }

}

How to Check Code Coverage of Apex Class in Salesforce

To ensure your code is solid, Salesforce requires at least 75% code coverage in your test classes before you can deploy. You can check this in the Developer Console under the Tests tab

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top