0

I am new to triggers. I saw an example where during inserting a contact a trigger set its Phone as Parent Account's Phone using the following code

trigger conTrigger on Contact(before insert){
    Set<ID> accIds = new Set<ID>();
    for(Contact con : Trigger.new){
        if(!String.isBlank(con.AccountId){
            accIds.add(con.AccountId);
        }
    }

    Map<Id, Integer> acctMap = new Map<Id, Integer>();
    List<Account> accList = [select Id, Phone from Account where Id in: accIds];

    for(Account a: accList){
        acctMap.put(a.id, a.Phone);
    }

    for(Contact con: Trigger.new){
        con.OtherPhone = acctMap.get(con.AccountId);
    }
}

I don't understand the below part

if(!String.isBlank(con.AccountId){
    accIds.add(con.AccountId);
}

I mean this is a before trigger right? The record still technically is not created but we are simply accessing the newly inserted values in the present context. Then how is the con.AccountId accessible at this moment when record still does not exist? Is it because from the UI perspective we are creating the contact from the Account related section so accountId is available?

1 Answer 1

1

It is only the record's own Id that is undefined in the before phase for insert. All other fields set by the code that performed the DML insert are naturally already set when the trigger is called.

All related objects must already exist in order to be linked to the record, which means they have an Id.

So here the code doing the insert (which could be standard or custom UI or REST API etc.) is expected to have already populated the Account Lookup. Of course this may not have been set for some Contacts. The isBlank is addressing this latter point (in a bizarre way though; a Lookup field is either NULL or an ID, it cannot be whitespace).

I would change the code gathering the related Account IDs to:

if (con.AccountId != null) {
  accIds.add(con.AccountId);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .