You need to sign in to do that
Don't have an account?
SalesforceLearner
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 !!
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; } }
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.
Do not do this
Lead aux = new Lead(Id = a.Id);
aux.Opportunity__c = opp[0].Id;
Instead do this
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.