Using the Related Object Accessor Field to Work with a Parent Object
When writing business logic in a child object like Activity
, you can
access its owning parent TroubleTicket
object using the related object accessor
field.
If the parent object is named TroubleTicket
, the related object accessor
field in Activity
will be named TroubleTicket_c
. It is best
practice to always store the parent object in a local variable as shown in the example below.
This ensures that no matter how many fields you access from the parent object or how many
times you reference it that you only retrieve it once.
// Store the parent object in a local variable
def ticket = TroubleTicket_c
// Now reference one or more fields from the parent
if (ticket.Status_c == 'Working' && ticket.Priority_c >= 2) {
// Do something here because the owning parent
// trouble ticket is high priority and being worked on.
}
Notice that since the child object cannot exist without an owning parent object, the
reference to the parent object will never be null
, so here instead of the
Groovy safe navigation operator (?.
) we can just use the normal dot operator
in the expression ticket.Status_c
.