Skip to content

AfterUndelete.ParentQuery

Reads fields of the record a lookup points to, such as a restored contact's account, without SOQL in your handler. The restored row holds only the lookup Id.

Interface

apex
public class AfterUndelete {
    public interface ParentQuery {
        Map<SObjectField, TriggerHandler.ParentFields> queryParentsOnAfterUndelete();
    }
}
  • queryParentsOnAfterUndelete(): called once per chunk, before the first handler runs; not called for a bypassed handler. Returns lookup field → the parent fields to load.

Example

apex
public with sharing class ContactWriter implements AfterUndelete.Writer, AfterUndelete.ParentQuery {
    public Map<SObjectField, TriggerHandler.ParentFields> queryParentsOnAfterUndelete() {
        return new Map<SObjectField, TriggerHandler.ParentFields>{ Contact.AccountId => TriggerHandler.ParentFields.with(Account.Name) };
    }

    public Boolean writeOnAfterUndeleteWhen(TriggerHandler.UndeleteRecord record) {
        return record.getNewParent('Account') != null;
    }

    public void writeOnAfterUndelete(TriggerHandler.UndeleteRecord record, TriggerHandler.UnitOfWork unitOfWork) {
        Account accountRecord = (Account) record.getNewParent('Account');

        unitOfWork.toInsert(new Task(WhatId = accountRecord.Id, Subject = 'Review contact of ' + accountRecord.Name));
    }
}

Good to Know

  • Read by relationship name. Use getNewParent('Account') for AccountId and getNewParent('Owner') for OwnerId. The name is case-sensitive.
  • Check for null. The parent is null when the lookup is empty or no record has that Id.
  • Declare every field you read. Reading a field that no handler declared throws an SObjectException. Add grandparent fields with .with('Owner', User.IsActive).
  • One query per chunk. One SOQL query on the restored records reads every declared parent, even when no record qualifies. A parent that query misses costs one more query per lookup.
  • No sharing. Parents are read in system mode, so a handler can see records the user cannot.