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
rvg170550rvg170550 

Referring input values in Apex Trigger

trigger After_Insert_On_Lead on Lead (after insert) {
Opportunity a = new Opportunity(name='Automatically created from Lead',
StageName = 'Pending',
CloseDate = date.newInstance(2008, 10, 28),
Nextstep = 'Visit');
Insert a;
}

How can I refer to the values of the inserted Lead ? For instance, I want to copy the value of the newly created Lead in an Opportunity field.


JimRaeJimRae
Look in the documentation for Trigger.New.  That is where you have access to the data in the inserted records.
There are some great samples in the doc.
rvg170550rvg170550
According the Apex Language Reference, Trigger.New cannot be used, since the record is already saved.
 
I want to create entries in a Event management from Leads, having a specific category; the entry in Leads is at that moment already in the database.
rvg170550rvg170550
Ignore my previous reply, this way it works, but 1 additional question:
 
trigger Before_Insert_On_Lead on Lead (before insert) {
for (Lead l_o : Trigger.New)
{  
Opportunity a = new Opportunity(name='Automatically created from Lead',
StageName = 'Pending',
CloseDate = date.newInstance(2008, 10, 29),
Location__c = 'MyPlace',
Nextstep = l_o.Company);
Insert a;
}
}
 
How can I update the opportunity afterwards, with the Id of the Lead, to establish a link between the 2 entries.
 
Thanks for your help
philbophilbo
Change your trigger to 'after insert', at which point the new Leads have their Ids, which you then can use in your Opportunity constructor.
JimRaeJimRae

Use an "after insert" instead, then the lead id will exist.

Code:
trigger After_Insert_On_Lead on Lead (after insert) {
for (Lead l_o : Trigger.New) 
{   
Opportunity a = new Opportunity(name='Automatically created from Lead', 
StageName = 'Pending', 
CloseDate = date.newInstance(2008, 10, 29), 
Location__c = 'MyPlace',
Nextstep = l_o.Company,
ConvertedOpportunityId=l_o.id);
Insert a;
}
}