0

I have a requirement in which I have to create a custom lookup field on lead object which selects the account Account__c and during the lead to account conversion I have to map the field with 'Parent Account' field of the account which is a standard field.So i am trying to write the code on before insert trigger that maps the custom lookup field of lead to the standard field of account.

trigger populateParentAccount on Account (before Insert){
    List<Lead> convertedLeads=[SELECT Id, ConvertedAccountID,Agency_account__c FROM Lead WHERE IsConverted=True AND ConvertedAccountId IN :trigger.new];
    Map<ID,ID> acctParentMap=new Map<ID,ID>(); 
    for (lead l: convertedleads){
        acctParentMap.put(l.ConvertedAccountId,l.Agency_account__c);
    } 
    for (account a:trigger.new){
     if (acctParentMap.containsKey(a.Id)){ 
     a.ParentId = acctParentMap.get(a.Id); 
     }
    }
}

But It is not working.. Please help..

2

This won't work in a before insert trigger, because the Account does not yet have an Id. You will need to use an after insert trigger to detect those records, then perform a recursive update to set the new values.

trigger populateParentAccount on account(after insert) {
  Account[] updates = new Account[0];
  Set<Id> accountIds = new Set<Id>();
  for(Lead record: [SELECT ConvertedAccountId, Agency_Account__c FROM Lead WHERE ConvertedAccountId = :Trigger.new ORDER BY ConvertedDate DESC]) {
    // Avoid multiple leads with same account 
    if(!accountIds.add(record.ConvertedAccountId)) { 
      updates.add(new Account(Id=record.ConvertedAccountId, ParentId=record.Agency_Account__c));
    }
  }
  update updates;
}
  • Hi sfdcfox,Thanks for your help. I am very new in Development side. Do I need to write Trigger handler to call the trigger? Thanks – Madhavi Jan 14 '20 at 18:42
  • @Madhavi No, triggers are called directly. The Trigger Handler frameworks often advocated ease unit testing in many situations, and allow more advanced logic, like detecting recursion, etc. – sfdcfox Jan 14 '20 at 19:35
  • Hi sfdc,I tested in my org , still parent Account is not getting populated. Looks like giving ConvertedAccountId as null.Do trigger work or I have to go through the batch Processing.. Thanks – Madhavi Jan 14 '20 at 22:28
  • @Madhavi I actually realized that you'll need to do that logic in an After Update Lead trigger. See this answer for more information. – sfdcfox Jan 15 '20 at 0:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.