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

Error in Trigger that tries to create Opportunity Line Items

Hello all, this is my first post here :) I'm writing an APEX Trigger that is supposed to create a Product Line Item when an opportunity is created. Here is what I did:


trigger AutoCreateInterviewer on Opportunity (after insert) {
List<OpportunityLineItem> OpportunityLineItems = new List<OpportunityLineItem>();
for (Opportunity newOpportunity: Trigger.New) {
if (newOpportunity.of_HD_Channels__c != null) {
OpportunityLineItems.add(new OpportunityLineItem(ProductId = '01t60000004Inzu',Opportunity = newOpportunity.Id,Quantity = 3,UnitPrice = 50));
insert OpportunityLineItems;


but it's not working, it gives me the following error:


Error: Compile Error: Invalid field ProductId for SObject OpportunityLineItem at line 5 column 74


Could you kindly tell me what the right syntaz is for what I need? Thanks in advance


My issue is with the arguments I'm passing, mainly the ProductId and the Opportunity I think because it saves fine without them there, please help :(

Sfd developerSfd developer



ProductId field in OpportunityLineItem object is unavailable as of version 3.0 and is only provided for backward compatibility. Instead, you have to use PricebookEntryId.


For Reference,


Hello there and thank you for the reply. I actually had changed the code to:


trigger AutoCreateInterviewer on Opportunity (after insert) {
    List<OpportunityLineItem> OpportunityLineItems = new List<OpportunityLineItem>();
    for (Opportunity newOpportunity: Trigger.New) {
        if (newOpportunity.of_HD_Channels__c != null) {
            OpportunityLineItems.add(new OpportunityLineItem(OpportunityId = newOpportunity.Id,PricebookEntryId ='01u60000006lcOjAAI',Quantity = 3,UnitPrice = 50));
    insert OpportunityLineItems;


and that worked except that it's going by the standard price book, I'm trying now to pass the right price book to the opportunity before the line items are created. If you have any suggestion it would be great :) Thanks.