In Apex we need a way to programmatically interact with custom and standard Salesforce sObject records. To do that, we need a datatype to represent the sObject. There are two categories of sObject datatypes available in Apex:
The first involves directly referencing the API name of a specific sObject type, like Account
, Opportunity
, or Project__c
. These are their own datatypes in Apex. So you can declare variables of this type and use them to store data.
Account acc = new Account(); Opportunity oppty = new Opportunity(); Project__c proj = new Project__c();
The other involves utilizing the generic sObject
datatype. This datatype serves as an abstract representation of any specific sObject datatype, thanks to the concept of inheritance, which we'll delve into during the Object-Oriented Programming (OOP) course. For now, it's important to understand that the sObject datatype is highly valuable when developing generic and reusable code.
// We'll explain why this is possible later sObject genericObjectInstance = new Lead(); genericObjectInstance.Id = '00Q8b000021WdiDEAS';
The syntax should look familiar if you've worked with classes before. Salesforce automatically provided us a class that matches the sObject's API name. So there's no need to create one ourselves. This means every field that exists on the sObject can be accessed from Apex.
// This is NOT needed!! Salesforce automatically makes this available to us public class Account() { public String Id; public String name; public String rating; public String type; public String customField__c; }
This class is still just a blueprint. It doesn't represent a record or hold data until you, the developer, create an instance of the class by creating an object. sObjects, Objects, types, rows, records; I'm sure you have all the straight in your head. (I'm being sarcastic). We'll take it slow in this course and figure it all out.
We're going to explore a lot, like:
How to set fields:
Account a = new Account(Name = 'FirstAccount'); a.type = 'Partner'; Account a2 = new Account(Name = 'SecondAccount'); a2.type = 'Customer'; a2.put('Website', 'CampApex.org');
And retrieve data:
private Decimal calculateRemainingBudget(Project__c proj){ return proj.Budget__c - proj.Spent__c; }
I don't mean to overwhelm you! I just wanted to give you a sneak peek of what is to come in this course. Good luck!