Populate child records field value on parent record
Populate child records field value on parent record by using apex trigger when child record is inserted.
***
trigger ContactTrigger on Contact (after insert) {
if(Trigger.isAfter && Trigger.isInsert){
ContactTriggerHandler.populateNameOnParent(Trigger.new);
}
}
***
***
// populate child records name on parent field when child record is inserted
public static void populateNameOnParent(List<Contact> contactList){
Map<Id,List<Contact>> contactWithAccId = new Map<Id,List<Contact>>();
Set<Id> accountIds = new Set<Id>();
List<Account> accountsList = new List<Account>();
String concatenateString;
for(Contact cont : contactList){
if(cont.AccountId != null)
{
accountIds.add(cont.AccountId); // get account id from contacts
}
}
// get all contacts related to account ids
if(accountIds.size() > 0){
for(Contact cont : [SELECT Id,AccountId,LastName
FROM Contact
WHERE AccountId IN: accountIds])
{
if(!contactWithAccId.containsKey(cont.AccountId))
{
contactWithAccId.put(cont.AccountId,new List<Contact>());
}
contactWithAccId.get(cont.AccountId).add(cont);
}
}
// get account records
if(accountIds.size() > 0){
for(Account acct : [SELECT Id,Contact_Names__c
FROM Account WHERE Id IN: accountIds])
{
concatenateString = '';
// populate all contact last name on parent record field
if(contactWithAccId.containsKey(acct.Id) && contactWithAccId.get(acct.Id).size() > 0)
{
for(Contact cont : contactWithAccId.get(acct.Id))
{
if(!concatenateString.contains(cont.LastName))
{
concatenateString = concatenateString + cont.LastName + ',';
}
}
concatenateString = concatenateString.removeEnd(',');
acct.Contact_Names__c = concatenateString;
}else{
acct.Contact_Names__c = null;
}
accountsList.add(acct);
}
}
try{
if(accountsList.size() > 0){
UPDATE accountsList;
}
}catch(Exception ex){
System.debug('exception^^' + ex.getMessage());
}
}
***
Note:
We can also remove any record name when that record is deleted. We have to pass Trigger.old list in method parameter.
Comments
Post a Comment