APEX & SOQL & SOSL - astromechanic/cheat_sheets GitHub Wiki

Find out child relationship name:

for (ChildRelationship relation : SObjectType.ObjectName.getChildRelationships())
    System.debug(relation.getRelationshipName());

Inline SOQL: Insert an account using anonymous Apex:


Account acct = new Account(
    Name='SFDC Computing',
    Phone='(415)555-1212',
    NumberOfEmployees=50,
    BillingCity='San Francisco');
insert acct;

SOQL using Query Editor:


select Name, Phone from Account where Name='Acme'
select fields(all) from OrderItem limit 200
select Name, Phone from Account where (Name='Acme' and NumberOfEmployees>50)
select Name from Account where Name like 'Acme%' 

Collections

List:

  • ordered
  • every element has an index
  • any data type
  • can contain duplicates
List<Integer> listOfNumbers = new List<Integer>();
listOfNumbers.add(1);
listOfNumbers.add(2);

Set:

  • unordered
  • no duplicates
  • any data

Map:

  • key-value pairs
  • keys are unique
Map<Integer, String> mapOfStrings = new Map<Integer, String>();
mapOfStrings.put(1, 'cat');
mapOfStrings.put(2, 'dog');
mapOfStrings.put(3, 'fish');

Random useful things:

Datetime currentDateTime = Datetime.now();
switch on expression{
   when value1 {
      ...
   }
   when value2 {
      ...
   }
}

Use @InvocableMethod annotation with a label attribute to allow tools like Process Builder to execute the method.

@InvocableMethod(label='Change Price')
public static void changePrice(..) {
   ...
}

Apex Triggers

https://trailhead.salesforce.com/content/learn/modules/apex_triggers/apex_triggers_intro?trailmix_creator_id=violettaivanova&trailmix_slug=b-2-b-lightning-developer

Apex Triggers are active by default when created.

Syntax:

trigger TriggerName on ObjectName (trigger_events) {

}

Events:

  • before insert

  • before update

  • before delete

  • after insert

  • after update

  • after delete

  • after undelete

Before triggers are used to update or validate record values before they’re saved to the database.

After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.

Context Variables Trigger.New - all records that were inserted in insert or update triggers. Trigger.Old - old versions of sObjects before they were updated in update triggers, or a list of deleted sObjects in delete triggers.

Boolean context variables: Trigger.isInsert

Trigger.isBefore

Trigger.isAfter

Trigger.isDelete

Trigger.isUpdate

Trigger.isUndelete

Call external web service out of trigger

Use the class marked with @future(callout=true) annotation

Limits

100 SOQL queries for synchronous Apex

200 SOQL queries for asynchronous Apex.

200 records a a time - executed by trigger

150 DML calls in one transaction

50 million records in Database.QueryLocator

SOSL

FIND {SFDC} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName,Department)

Get picklist values

List<String> caseTypeValues = new List<String>();
Schema.DescribeFieldResult fieldResult = Case.Type.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
  caseTypeValues.add(pickListVal.getLabel());
}

Apex Callouts

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if(response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for(Object animal: animals) {
        System.debug(animal);
    }
}

Test GET methods

@isTest
private class AnimalsCalloutsTest {
    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result, 'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(), 'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(), 'The array should only contain 3 items.');          
    }   
}

To test a POST callout, implement HttpCalloutMock:

@IsTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

and use it in the test class:

@IsTest static void testPostCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock()); 
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse response = AnimalsCallouts.makePostCallout();
        // Verify that the response received contains fake values
        String contentType = response.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = response.getBody();
        System.debug(response.getBody());
        String expectedValue = '{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}';
        System.assertEquals(expectedValue, actualValue);
        System.assertEquals(200, response.getStatusCode());
    }

Get map from a SOQL query:

Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);

Convert list to map:

Map<Id,OBJ_TYPE> mapFromList = new Map<Id,OBJ_TYPE>(List_object_variable);

Get picklist values and labels:

public static Map<String, String> getPicklistFieldValues() {
    Map<String, String> options = new Map<String, String>();
    Schema.DescribeFieldResult fr = ObjectName.FieldName.getDescribe();
    List<Schema.PicklistEntry> plValues = fr.getPicklistValues();
    for (Schema.PicklistEntry p : plValues) {
        options.put(p.getValue(), p.getLabel());
    }
    return options;
}
⚠️ **GitHub.com Fallback** ⚠️