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
SalesforceLearnerSalesforceLearner 

after Update trigger to insert record and update field.

I wrote a trigger on lead object where it Inserts opportunity record and update the Lookup field on Lead with Opportunity ID.

Here is my code it is inserting Opportuinity Record but it is not updating the field. And I want to use after Update only !! 
 
public class TriggerHelper {
 
    public static boolean isExecuting = false;
   
 
    public static void updateValues(){
  List<Opportunity> opp = new List<Opportunity>();
        if( TriggerHelper.isExecuting ){
            // if was executed durinListg the same context 
            // avoid recursion
            return;
        }
 
        TriggerHelper.isExecuting = true; 
        
        //list of new instance of object to update. 
        Lead[] lds = new Lead[]{};
      System.debug('@@@@@@@@@@@@@@@@@@@@@@@@@@@@');
        for (Lead a : (List<Lead>)Trigger.new) {  
        if(a.LastName == 'test'){
    
    Opportunity op = new Opportunity();
    op.Name = a.LastName;
    op.CloseDate= System.today()+20;
    op.StageName = 'Prospecting';
    opp.add(op);
    
    System.debug('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'+op);

            //here the magic by creating a new instance using the same id
            Lead aux  = new Lead(Id = a.Id);       
            aux.Opportunity__c =  opp[0].Id;
            
     
        System.debug('%%%%%%%%%%%%%%%%%%%%%%');
        } 
        
    }   
        //then update the new instance list. 
        Insert opp;
        Update lds;
 
    }
 
}


 
Marek Kosar_Marek Kosar_
hi

that's because Id is populated AFTER record is inserted....so first you have to insert opportunity and after that, use the `magic` - set opportunity field on lead and finally, update Lead.
Caleb SidelCaleb Sidel
You've created a nice list called "lds" but you never populate it. Also you don't have to create new Lead, you already have a reference to it with the variable 'a'. 

Do not do this
//here the magic by creating a new instance using the same id
Lead aux  = new Lead(Id = a.Id);       
aux.Opportunity__c =  opp[0].Id;

Instead do this
//here the magic by creating a new instance using the same id
a.Opportunity__c =  opp[0].Id;
lds.add(a);


PS: I'd change "a" to be called "aLead" and I'd change "lds" to be called "leadsToUpdate" only because more descriptive variables names are always good.