June 19, 2020

Sample Trigger to update Account after Lead Conversion in Salesforce

Below trigger fetches all the Accounts when the Leads are converted. It sets the Record Type Id to External Account Record Type Id if the Account's Record Type Id is not External Account Record Type Id.

Sample code:

trigger LeadTrigger on Lead ( after update ) {

    Set < Id > setAccountIds = new Set < Id >();
   
    for ( Lead objLead : trigger.new ) {
       
        /* Getting Account Ids from the Lead after conversion .
           ConvertedAccountId in Lead contains the Account Id to which the Lead is converted.
        */
        if ( objLead.IsConverted && objLead.IsConverted != trigger.oldMap.get( objLead.Id ).IsConverted )
            setAccountIds.add( objLead.ConvertedAccountId );
   
    }
   
    if ( setAccountIds.size() > 0 ) {
   
        Id extRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get( 'External' ).getRecordTypeId();
        List < Account > listAcctForUpdate = new List < Account >();
       
        /* Fetching the accounts which are created as part of lead conversion and record type is not External */
        for ( Account objAccount : [ SELECT Id, RecordTypeId FROM Account WHERE Id IN: setAccountIds AND RecordTypeId !=: extRecordTypeId ] ) {
           
            /* Setting the Record Type Id to Account's External Record Type Id */
            listAcctForUpdate.add( new Account( Id = objAccount.Id, RecordTypeId = extRecordTypeId ) );
       
        }
       
        if ( listAcctForUpdate.size() > 0 )
            update listAcctForUpdate;
   
    }

}

No comments:

Post a Comment