Using the Related Object Accessor Field to Work with a Referenced Object
When writing business logic for an object like TroubleTicket that has a
lookup field like Contact or AssignedTo, you can access the
object referenced by the lookup field using the respective lookup field's secondary related
object accessor field.
See Understanding Secondary Fields Related to a Dynamic Choice List Field for more information on this.
For the Contact and AssignedTo lookup fields, the secondary
related object accessor fields are named Contact_Obj_c and
AssignedTo_Obj_c, respectively. The example below shows how to reference
the two lookup objects from script written in the context of TroubleTicket,
and access one of each's fields. It is best practice to always store the referenced lookup
object in a local variable as shown in the example below. This ensures that no matter how many
fields you access from the related object you only retrieve it once.
// Store the contact object and assignedTo object in a local variable
def customer = Contact_Obj_c
def supportRep = AssignedTo_Obj_c
// Now reference one or more fields from the parent
if ((endsWith(customer?.EmailAddress_c,'.gov') ||
endsWith(customer?.EmailAddress_c,'.com')
)
&&
(startsWith(supportRep?.PhoneNumber_c,'(202)')||
startsWith(supportRep?.PhoneNumber_c,'(206)')
)
)
{
// Do something here because contact's email address
// is a government or business email and assigned-to
// support rep is in 202 or 206 Washington DC area code
}
Notice that since the dynamic choice list fields Contact_c and
AssignedTo_c might be optional, their value may be null
and consequently the value of the related object accessor may be null, too.
This is why the example is using the Groovy safe navigation operator (?.) to
reference fields of the related object in case either related object might be
null.