Apex Cheat Sheet Online

 Apex is a powerful language used for development on the Salesforce platform. Here’s a concise yet comprehensive cheat sheet to help you master Apex coding.



Basics

  1. Syntax:

    • Apex is case-insensitive.
    • Statements end with a semicolon (;).
  2. Variables:

    Integer count = 10; String name = 'Salesforce'; Boolean isActive = true;
  3. Comments:

    // Single-line comment /* Multi-line comment */

Data Types

  • Primitive Types: Integer, Double, Long, Date, Datetime, String, ID, Boolean
  • sObject Types: Any Salesforce object (e.g., Account, Contact)
  • Collection Types: List, Set, Map
  • Custom Types: User-defined classes, enums, interfaces

Collections

  1. List:

    List<String> names = new List<String>{'Alice', 'Bob', 'Charlie'}; names.add('Diana');
  2. Set:

    Set<Integer> ids = new Set<Integer>{1, 2, 3}; ids.add(4);
  3. Map:

    Map<Id, Account> accounts = new Map<Id, Account>{}; accounts.put(acc.Id, acc);

Control Flow

  1. If-Else:

    if (condition) { // code } else if (condition) { // code } else { // code }
  2. For Loop:

    for (Integer i = 0; i < 10; i++) { // code } for (Account acc : [SELECT Id, Name FROM Account]) { // code }
  3. While Loop:

    while (condition) { // code }

DML Operations

  1. Insert:

    Account acc = new Account(Name='Acme Inc'); insert acc;
  2. Update:

    acc.Name = 'Acme Corporation'; update acc;
  3. Delete:

    delete acc;
  4. Upsert:

    upsert acc;

SOQL (Salesforce Object Query Language)

  1. Basic Query:

    List<Account> accounts = [SELECT Id, Name FROM Account];
  2. Where Clause:

    List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :accId];
  3. Order By:

    List<Account> sortedAccounts = [SELECT Id, Name FROM Account ORDER BY Name ASC];
  4. Aggregate Functions:

    AggregateResult[] results = [SELECT COUNT(Id) total FROM Account]; Integer totalAccounts = (Integer)results[0].get('total');

SOSL (Salesforce Object Search Language)

List<List<SObject>> searchResults = [FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)];

Exception Handling

try { // code that might throw an exception } catch (DmlException e) { // handle the exception } finally { // code that runs regardless of whether an exception was thrown }

Apex Triggers

  1. Basic Structure:

    trigger AccountTrigger on Account (before insert, after insert, before update, after update, before delete, after delete) { if (Trigger.isBefore) { if (Trigger.isInsert) { // code } } }
  2. Context Variables:

    • Trigger.new: New records in insert/update
    • Trigger.old: Old records in update/delete
    • Trigger.newMap, Trigger.oldMap: Maps of IDs to records

Batch Apex

  1. Batch 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) { // code } global void finish(Database.BatchableContext bc) { // code } }
  2. Executing Batch:

    BatchExample batch = new BatchExample(); Database.executeBatch(batch);

Apex Scheduler

  1. Scheduler Class:

    global class ScheduledClass implements Schedulable { global void execute(SchedulableContext sc) { // code } }
  2. Scheduling:

    String cronExp = '0 0 12 * * ?'; // Every day at noon System.schedule('Daily Job', cronExp, new ScheduledClass());

Asynchronous Apex

  1. Future Method:

    @future public static void doFutureWork() { // code }
  2. Queueable Apex:

    public class QueueableExample implements Queueable { public void execute(QueueableContext context) { // code } } System.enqueueJob(new QueueableExample());

Custom Metadata Types

  1. Define Metadata:

    CustomMetadataType__mdt metadata = new CustomMetadataType__mdt(); metadata.DeveloperName = 'CustomSetting'; metadata.Label = 'Custom Setting';
  2. Query Metadata:

    List<CustomMetadataType__mdt> mdList = [SELECT DeveloperName, Label FROM CustomMetadataType__mdt];

Best Practices

  1. Bulkify Your Code: Always write code to handle multiple records.
  2. Avoid SOQL/DML in Loops: Move queries and DML operations outside loops.
  3. Use Collections: Use lists, sets, and maps to efficiently process records.
  4. Handle Exceptions: Always use try-catch blocks to manage exceptions.
  5. Use Custom Settings: Store and manage configuration data outside of code.
  6. Test Coverage: Write thorough unit tests to ensure at least 75% code coverage.

This cheat sheet covers essential aspects of Apex development, offering a solid foundation for anyone looking to master Salesforce Apex coding.

Post a Comment

0 Comments