Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Apex Basics

SObjects and Fields in Apex

Understand Salesforce objects, records and fields as Apex SObjects: standard and custom objects, field access, relationships, generic SObjects and the Schema class.

Salesforce stores data in objects, which are like database tables. An Account object holds companies, a Contact object holds people, and each row is a record. In Apex, every object is available as a data type called an SObject (Salesforce Object). This is what makes Apex special: database tables are part of the language, with no mapping layer to write.

Standard and custom objects

  • Standard objects come with Salesforce: Account, Contact, Lead, Opportunity, Case, Task, User and many more.
  • Custom objects are ones you create. Their API names end in __c, for example Invoice__c. Custom fields also end in __c: Account.Rating__c.
  • Relationship fields point to another object. A lookup field Account__c on a custom object has the relationship name Account__r, which lets you reach the parent's fields.

Each object has fields of types such as Text, Number, Currency, Date, Checkbox, Picklist and Lookup. Each field has an API name (what code uses) and a label (what users see).

flowchart LR
    A["Account<br/>Id, Name, Industry"] --> C["Contact<br/>Id, LastName, AccountId"]
    A --> O["Opportunity<br/>Id, Name, StageName, AccountId"]
    C --> T["Task<br/>Id, Subject, WhoId"]

One Account can have many Contacts and Opportunities. The child holds the parent's Id in a lookup field such as AccountId.

Creating and using an SObject

Java
Account acc = new Account();
acc.Name = 'Acme Corp';
acc.Industry = 'Energy';
acc.AnnualRevenue = 5000000;

Account acc2 = new Account(Name = 'Globex', Industry = 'Technology');   // constructor style

Dot notation reads and writes fields. Creating the variable does not save anything: the record exists only in memory until you run a DML statement such as insert acc;.

After a record is saved, its Id field is filled in. Before that, acc.Id is null.

Records are not all fields

When you query a record, you only get the fields you ask for. Reading a field you did not query throws System.SObjectException: SObject row was retrieved via SOQL without querying the requested field. The fix is to add the field to the SELECT list. SOQL basics shows how.

Relationships in code

From a child, use the relationship name to reach the parent's fields:

Java
Contact c = [SELECT LastName, Account.Name, Account.Industry FROM Contact LIMIT 1];
System.debug(c.Account.Name);

From a parent, the children come back as a list under the plural relationship name:

Java
Account a = [SELECT Name, (SELECT LastName FROM Contacts) FROM Account LIMIT 1];
for (Contact con : a.Contacts) {
    System.debug(con.LastName);
}

For a custom lookup, the relationship name is the field name with __c replaced by __r.

Generic SObject and casting

SObject is the parent of all objects. You can hold any record in an SObject variable and read fields with get('FieldName'):

Java
SObject record = new Account(Name = 'Acme');
String name = (String) record.get('Name');
record.put('Industry', 'Energy');
Account typed = (Account) record;        // cast back to the specific type

Generic code is useful for utilities that work on any object, such as a reusable audit logger.

The Schema class: describing objects

The Schema namespace lets code ask Salesforce about its own metadata:

Java
Schema.DescribeSObjectResult d = Account.SObjectType.getDescribe();
System.debug(d.getLabel());                      // 'Account'
System.debug(d.isCreateable());                  // can this user create accounts?
Map<String, Schema.SObjectField> fields = d.fields.getMap();
System.debug(fields.keySet());

Describe calls also let you check field-level security (isAccessible(), isUpdateable()) before touching data, a security topic we return to later.

Stand-in: a generic record

The Java stand-in below models an SObject as a typed record plus a generic Map view, so you can see why get and put are convenient and where they are risky.

Java Stand-in (Java): typed fields versus generic get/put

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Naming and API versions

Use the API name in code and queries, not the label. You can find API names in Setup under Object Manager, or with the VS Code org browser. Field names are case-insensitive, but keeping the exact casing (BillingCity) makes code easier to read.

Common mistakes

  1. Forgetting that an unsaved record has no Id.
  2. Reading a field not included in the query.
  3. Using the label ("Annual Revenue") instead of the API name (AnnualRevenue).
  4. Forgetting __c on custom fields.
  5. Expecting a missing parent to give an empty object: contact.Account is null when there is no parent, so contact.Account.Name throws. Use contact.Account?.Name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What suffix do custom objects and fields have in their API names?

    Custom objects and fields end in __c. __r is for relationship names.
  2. 2. When does a new Account variable get an Id?

    The Id is assigned by the database when the record is inserted.
  3. 3. What error appears when you read a field that was not in the SELECT list?

    Salesforce raises SObjectException because that field was not retrieved.
  4. 4. How do you read an Account's name from a Contact record c?

    Use the relationship name Account, and include Account.Name in the query.

Summary

  • Objects are tables, records are rows, fields are columns; each is an SObject in Apex.
  • Standard objects have plain names; custom ones end in __c (fields) and __r (relationship names).
  • A new record is only in memory until you insert it, and a query returns only the fields you list.
  • get, put and Schema describe calls enable generic code.

Next: SOQL Basics