You need to sign in to do that
Don't have an account?
Get record ID when trigger fires!
Hey Guys,
Trying to get my head around apex triggers, would appreciate some help:
To create a specific product after opportunity is created, but I can't get the id.
My Code:
trigger AddProduct on Opportunity (after insert) { OpportunityLineItem bLineItem = new OpportunityLineItem(); bLineItem.quantity = 1; bLineItem.UnitPrice = 100.00; bLineItem.Opportunityid = ???????????; bLineItem.pricebookentryid = '01uT0000000vtvnIAA'; Insert bLineItem;}
I want to insert the ID from a newly created opportunity.
Thanks
Hi Rumdumdum,
I think this code may help you get what you're after. It's bulkified to handle batch inserts of Opportunities too. Based on your code, I'm assuming that you want to add a specific product to each Opp after the Opp is created.
trigger Opportunity on Opportunity (after insert) {
//Create a List to hold Opp Line Items to be inserted
List<OpportunityLineItem> blineItems = new List<OpportunityLineItem>();
//use for loop to iterate through all opportunities in trigger
for(Opportunity o : trigger.new){
//add an Opp Line Item for each Opportunity, using o.Id to relate the OLI to the Opp.
blineItems.add(new OpportunityLineItem(quantity = 1,
UnitPrice = 100.00,
OpportunityId = o.Id,
//not good to use a static ID...but that's a topic for another post
pricebookentryid = '01uT0000000vtvnIAA'));
}
insert blineItems;
}
All Answers
Hi Rumdumdum,
I think this code may help you get what you're after. It's bulkified to handle batch inserts of Opportunities too. Based on your code, I'm assuming that you want to add a specific product to each Opp after the Opp is created.
trigger Opportunity on Opportunity (after insert) {
//Create a List to hold Opp Line Items to be inserted
List<OpportunityLineItem> blineItems = new List<OpportunityLineItem>();
//use for loop to iterate through all opportunities in trigger
for(Opportunity o : trigger.new){
//add an Opp Line Item for each Opportunity, using o.Id to relate the OLI to the Opp.
blineItems.add(new OpportunityLineItem(quantity = 1,
UnitPrice = 100.00,
OpportunityId = o.Id,
//not good to use a static ID...but that's a topic for another post
pricebookentryid = '01uT0000000vtvnIAA'));
}
insert blineItems;
}
Thank you Guys, it's nice to see that there's help for newcomers here! :)
And Luke, much appreciated for your input!
Thanks