Sunday, 11 November 2018

Trigger to update child field with parent field


This trigger is to update the Child field with Parent field. In the below example, we will be updating the Contact's LastName with Account's Name.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
trigger UpdateChildWithParent on Contact (Before insert, before update) {
 
    Set<id> AccId = New Set<id>();
    Map<Id,Account> AccountMap = New Map<Id,Account>();

    
    For(contact contact : trigger.new){
        AccId.add(contact.AccountId);
    }
    
    for(Account acc : [Select Id,Name from Account WHERE ID IN : AccId]){
        AccountMap.put(acc.Id,Acc);
    }

    For(contact contact : trigger.new){
        if(AccountMap.containsKey(Contact.AccountId)){
            contact.LastName = AccountMap.get(contact.AccountId).Name;
        }
    }

}

No comments:

Post a Comment