function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gaurav  PuranikGaurav Puranik 

Trigger on Lead

Hi Friends,

I want to make trigger on Lead that whenevr my Lead is created Account should also create. And after the creation of Account I want that same account should map in account__c field of my lead.

I created trigger on this but that I created for before insert case. Now I want same thing to happen in After insert case, bcoz the trigger is failing by validation rule in before case.

Can anyone help me on this..
Trigger which I wrote..
trigger BaseLineTrigger on Lead (before insert, after insert,before update,after update) {
   
       LeadHandler objLead = new LeadHandler();
       
    if(Trigger.isBefore && Trigger.isInsert) {
        objLead.addAccount(Trigger.New); 
     }
}

Handler Class :-

public class LeadHandler {
    
    public LeadHandler(){}

    public void addAccount(list<Lead> lstLead) {
        map<Integer,Account> mapAccount = new map<Integer,Account>();
        integer i =0;
       
            for(Lead objLead : lstLead) {
                Account objAccount = new Account();                     
                if(objLead.status =='Base Line' && objLead.Origin__c != 'Mobile'){
                    system.debug('================'+objLead);
                        mapUserBaseNo.put(objLead.OwnerId, mapUserBaseNo.get(objLead.OwnerId)+1);
                    if(objLead.FirstName!= null)
                        objAccount.Name = objLead.FirstName + ' ' + objLead.LastName;
                    else
                       objAccount.Name = objLead.LastName;
                       objAccount.Contact_Number__c = objLead.Phone;
                    objAccount.Date_of_Birth__c  = objLead.Date_Of_Birth__c;
                    objAccount.BillingCity = objLead.City;  
                    objAccount.BillingCountry =objLead.Country;
                    objAccount.BillingStreet = objLead.Street;
                    objAccount.BillingState = objLead.State;
                    objAccount.BillingStateCode = objLead.StateCode;
                    objAccount.BillingPostalCode = objLead.PostalCode;
                    objAccount.Disability__c = objLead.Disability__c;
                    objAccount.Profile_Pictures__c = objLead.Image__c;
                    objAccount.Parent_Guardian_name__c = objLead.Company;
                    objAccount.Village__c = objLead.Village__c;
                    mapAccount.put(i,objAccount);
                }
                 i++; 
            }
        
        insert mapAccount.values();          
        
        integer j =0;
            for(Lead objLead : lstLead){
                if(mapAccount.containsKey(j))
                    objLead.Account__c = mapAccount.get(j).id;
                    j++;
             }
    }
Best Answer chosen by Gaurav Puranik
sandeep sankhlasandeep sankhla
Hi gaurav,

Please use below code for reference, I have implemented the same and it is createing account when My lead is created and then sme account id it is populating in lead field..
 
public void onAfterInsert(List<Lead> lstLeads)
	{
		Map<Id, Account> mapLeadIdToAcc = new Map<Id, Account>();
		
		list<Lead> lstLeadToUpdate = new list<Lead>();
		
		for(Lead objLead : lstLeads)
		{
			Account objAccount = new Account();         
			
			 if(objLead.status =='Base Line' && objLead.Origin__c != 'Mobile')
			 {
			 	if(objLead.FirstName!= null)
                        objAccount.Name = objLead.FirstName + ' ' + objLead.LastName;
                    else
                       objAccount.Name = objLead.LastName;
                       
                    objAccount.Contact_Number__c = objLead.Phone;
                   objAccount.Date_of_Birth__c  = objLead.Date_Of_Birth__c;
                    objAccount.BillingCity = objLead.City;  
                    objAccount.BillingCountry =objLead.Country;
                   objAccount.BillingStreet = objLead.Street;
                   objAccount.BillingState = objLead.State;
                   objAccount.BillingStateCode = objLead.StateCode;
                    objAccount.BillingPostalCode = objLead.PostalCode;
                    objAccount.Disability__c = objLead.Disability__c;
                    objAccount.Profile_Pictures__c = objLead.Image__c;
                    objAccount.Parent_Guardian_name__c = objLead.Company;
                    objAccount.Village__c = objLead.Village__c;
                    mapLeadIdToAcc.put(objLead.Id, objAccount);
                    
			 }
		}
		
		insert mapLeadIdToAcc.values();
		
		for(Id iddd : mapLeadIdToAcc.keyset())
		{
			Lead objlead = new Lead(Id = iddd);
			objlead.Aa__c = mapLeadIdToAcc.get(iddd).Id;
			lstLeadToUpdate.add(objlead);
			
		}
		
		Update lstLeadToUpdate;
	}

    Please provide your field API names to correct syntax errors and let me know if you still face the issue...

for your question, yes we can update the same field, there is nothing wromng in that..just replace your insert methdo with above method and check..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 

All Answers

ManojjenaManojjena
HI Gaurav,

Is there any requirment that you need to update on account once you update lead ?
sandeep sankhlasandeep sankhla
Hi Gaurav,

You should use After insert on this case..Can you let me know if your should be fire on after update also..

Because after insertion of lead we will create the account and relate that to Lead and same account acount Id we need to populate in Lead account field..
this we can handle by After insert on lead..

But if your trigger should also fire on After Update then it will go in recurrsion but that also we can handle by recurrsion handler..but if after update on lead is not required then we can simply avoid that..

Please confirm these things so I can help you out ..

Thanks,
Sandeep
Gaurav  PuranikGaurav Puranik
Hi Manoj and Sandeep..Yes I need the same in update case also.

I have tried to write trigger for after insert, after update..wrote recurssion handler class for the same but I am getting this error

"Trigger: execution of AfterInsert caused by: System.FinalException: Record is read-only:"

I searched this on net and found that we cannot update field on same record on which we are creating trigger, in 'after insert' case. Is this true or am I doing some mistake?
sandeep sankhlasandeep sankhla
Hi gaurav,

Please use below code for reference, I have implemented the same and it is createing account when My lead is created and then sme account id it is populating in lead field..
 
public void onAfterInsert(List<Lead> lstLeads)
	{
		Map<Id, Account> mapLeadIdToAcc = new Map<Id, Account>();
		
		list<Lead> lstLeadToUpdate = new list<Lead>();
		
		for(Lead objLead : lstLeads)
		{
			Account objAccount = new Account();         
			
			 if(objLead.status =='Base Line' && objLead.Origin__c != 'Mobile')
			 {
			 	if(objLead.FirstName!= null)
                        objAccount.Name = objLead.FirstName + ' ' + objLead.LastName;
                    else
                       objAccount.Name = objLead.LastName;
                       
                    objAccount.Contact_Number__c = objLead.Phone;
                   objAccount.Date_of_Birth__c  = objLead.Date_Of_Birth__c;
                    objAccount.BillingCity = objLead.City;  
                    objAccount.BillingCountry =objLead.Country;
                   objAccount.BillingStreet = objLead.Street;
                   objAccount.BillingState = objLead.State;
                   objAccount.BillingStateCode = objLead.StateCode;
                    objAccount.BillingPostalCode = objLead.PostalCode;
                    objAccount.Disability__c = objLead.Disability__c;
                    objAccount.Profile_Pictures__c = objLead.Image__c;
                    objAccount.Parent_Guardian_name__c = objLead.Company;
                    objAccount.Village__c = objLead.Village__c;
                    mapLeadIdToAcc.put(objLead.Id, objAccount);
                    
			 }
		}
		
		insert mapLeadIdToAcc.values();
		
		for(Id iddd : mapLeadIdToAcc.keyset())
		{
			Lead objlead = new Lead(Id = iddd);
			objlead.Aa__c = mapLeadIdToAcc.get(iddd).Id;
			lstLeadToUpdate.add(objlead);
			
		}
		
		Update lstLeadToUpdate;
	}

    Please provide your field API names to correct syntax errors and let me know if you still face the issue...

for your question, yes we can update the same field, there is nothing wromng in that..just replace your insert methdo with above method and check..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
This was selected as the best answer
Gaurav  PuranikGaurav Puranik
Thanks Sandeep now everything is working perfect. Thanks for the help.