AfterDelete.PriorParentQuery
Read fields of the parent the old row pointed to, such as a contact's former account, without SOQL in your handler.
Signature
apex
public interface PriorParentQuery {
Map<SObjectField, TriggerTypes.ParentFields> queryPriorParentsOnAfterDelete();
}queryPriorParentsOnAfterDelete(): called once per chunk, before the first handler runs. Returns lookup field → the parent fields to load.
Example
apex
public with sharing class ContactWriter implements AfterDelete.Writer, AfterDelete.PriorParentQuery {
public Map<SObjectField, TriggerTypes.ParentFields> queryPriorParentsOnAfterDelete() {
return new Map<SObjectField, TriggerTypes.ParentFields>{ Contact.AccountId => TriggerTypes.ParentFields.with(Account.Name) };
}
public Boolean writeOnAfterDeleteWhen(TriggerTypes.DeleteRecord record) {
return record.getOldParent(Contact.AccountId) != null;
}
public void writeOnAfterDelete(TriggerTypes.DeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
Account previousAccount = (Account) record.getOldParent(Contact.AccountId);
unitOfWork.toInsert(new Task(WhatId = previousAccount.Id, Subject = 'Contact left ' + previousAccount.Name));
}
}Rules
- Read by lookup field. Pass the lookup field you declared, such as
getOldParent(Contact.AccountId). For the Id alone, read the lookup fromgetOldSObject(). - Read as it is now. The parent is queried when the trigger runs, so its fields show current values. It is null when the lookup was empty or the parent no longer exists.
- Only declared fields. The parent holds the declared fields and its
Id. Reading any other field throws anSObjectException. - One query per lookup. Each declared lookup costs at most one SOQL query per chunk, when a handler first reads its parent. A lookup no handler reads costs nothing.
WARNING
Parents are read in system mode without sharing, so a handler can see records the user cannot.
