Sub topic 11
Creating and inspecting records in Apex
This chapter assumes you know what objects, fields and API names are, and that you can read a basic SOQL query. You should also have the Invoice__c object from earlier chapters, with a text Name field, a lookup field Account__c, a number field Amount__c and a picklist field Status__c.
Records as sObjects
Apex is Salesforce's server-side programming language. In Apex, every record is an sObject, which is a typed instance of an object. Standard and custom objects use the same model. Account is an sObject type, and so is Invoice__c. You set fields with the constructor or with dot notation, using each field's API name.
DML (Data Manipulation Language) is the set of Apex statements that write to the database: insert, update, delete and undelete. This chapter focuses on insert.
Creating a standard record and a linked custom record
The code below creates an Account, then an Invoice that points to it. After insert acc runs, Salesforce fills in acc.Id. You need that Id to populate the lookup field on the child record.
Account acc = new Account(Name = 'Acme Corp');
insert acc;
Invoice__c inv = new Invoice__c(
Name = 'INV-0001',
Account__c = acc.Id,
Amount__c = 1200,
Status__c = 'Open'
);
insert inv;The order matters. If you insert the invoice first, acc.Id is still null, and the lookup stays empty.
Inspecting objects with schema describe
Sometimes you need to ask the platform what an object is rather than assume. Schema describe methods return metadata about an object. isCustom() returns true for custom objects.
Schema.DescribeSObjectResult accountDescribe = Account.SObjectType.getDescribe();
Schema.DescribeSObjectResult invoiceDescribe = Invoice__c.SObjectType.getDescribe();
System.debug(accountDescribe.getName() + ' custom? ' + accountDescribe.isCustom());
System.debug(invoiceDescribe.getName() + ' custom? ' + invoiceDescribe.isCustom());Run this in the Developer Console's Execute Anonymous window and open the debug log. You should see Account custom? false and Invoice__c custom? true. The same describe result also exposes labels, field maps and the current user's access. Code that must work across many objects often relies on it.
Reading records back
After inserting, you can query the records and follow relationships. A query returns a list of sObjects, and a parent field is reached through the __r relationship name.
List<Invoice__c> openInvoices = [
SELECT Name, Amount__c, Status__c, Account__r.Name
FROM Invoice__c
WHERE Status__c = 'Open'
];
for (Invoice__c i : openInvoices) {
System.debug(i.Name + ' belongs to ' + i.Account__r.Name);
}A field you leave out of the SELECT list is not loaded. Reading it throws a System.SObjectException. This is a common error when code uses a field that the query did not request.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `REQUIRED_FIELD_MISSING` | A required field, such as Account Name, was not set | Populate every required field before `insert` |
| `INVALID_FIELD` or a compile error | The API name is wrong, for example `Amount` instead of `Amount__c` | Use the exact API name, including `__c` |
| `System.SObjectException` | A field was read that the query did not select | Add the field to the `SELECT` list |
| `INSUFFICIENT_ACCESS` | The user lacks object or field permissions | Check the permission set, or use sharing rules |
Bulk-safe habits
Apex enforces governor limits, which cap how many DML statements and queries one transaction can run. You can insert a whole list in one statement. Do this instead of putting insert inside a loop.
List<Invoice__c> invoices = new List<Invoice__c>();
for (Integer n = 2; n <= 5; n++) {
invoices.add(new Invoice__c(
Name = 'INV-000' + n,
Amount__c = 100 * n,
Status__c = 'Open'
));
}
insert invoices;Exercise
A developer inserts an Invoice_c with `Account_c = acc.Id before running insert acc;`. What happens to the lookup, and how do they fix it?
Show answer
acc.Id is still null at that point, so the lookup field is empty on the saved invoice. The fix is to run insert acc; first so Salesforce assigns the Id, and then create and insert the invoice.
Exercise
Why is it better to call insert invoices; once on a list than to call insert inv; inside a loop?
Show answer
Each DML statement counts against the governor limit for the transaction. One statement on a list uses a single DML call, while a loop can exceed the limit and fail.