Skip to main content
Jagriti Kukreti (RBC) が「#Apex」で質問
Please help me with a trigger to populate latest contact record's email id on account field
3 件の回答
  1. 2019年5月24日 7:50
    Hi,

    Try the below code it works for me:

    Trigger:

    trigger YaTriggerContact on Contact (before insert) {

    if(Trigger.isInsert){

    YaTestClassConatct.updateConatctAccount(trigger.new);

    }

    }

    Trigger-Handler:

    public class YaTestClassConatct {

    public static void updateConatctAccount(List<Contact> conList){

    if(conList.size()>0){

    try{

    Set<Id> acIdSet=new Set<Id>();

    Map<Id,String> accountVsConatctMap=new Map<Id,String>();

    List<Account> accList=new List<Account>();

    for(Contact con:conList){

    if(con.AccountId!=null){

    acIdSet.add(con.AccountId);

    accountVsConatctMap.put(con.AccountId,con.Email);

    }

    }

    if(acIdSet.size()>0){

    accList=[Select Id,Name,Email__c From Account Where Id In:acIdSet Limit 10000];

    }

    if(accList.size()>0){

    for(Account acc:accList){

    if(accountVsConatctMap.containsKey(acc.Id)){

    acc.Email__c=accountVsConatctMap.get(acc.Id);

    }

    }

    }

    update accList;

    }

    catch (Exception ex) {

    system.debug('Error->' + ex.getMessage() + '--LineNo->' + ex.getLineNumber());

    }

    }

    }

    }

    I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

    Thanks,

    Ajay Dubedi
0/9000