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
Mooda MayuMooda Mayu 

How to insert product and price book under opportunity using apex code through Anonymous window.

How to insert product and pricebook under opportunity using apex code through Anonymous window.
Best Answer chosen by Mooda Mayu
Mooda MayuMooda Mayu
Hello, I found the answer.

Opportunity objOpporunity = new Opportunity();
objOpporunity.Name = 'Test Opporutnity';
objOpporunity.AccountId = objAccount.Id;
objOpporunity.StageName = 'Closed Won';
objOpporunity.CloseDate = system.Today();
Insert objOpporunity;

Product2 objProduct = new Product2();
objProduct.Name = 'Test';
objProduct.Description = 'Test';
Insert objProduct;
 

PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true];
PricebookEntry objPBEntry = new PricebookEntry(Pricebook2Id = pb2Standard.Id, Product2Id=objProduct.Id,UnitPrice=500,IsActive=true);
Insert objPBEntry;

OpportunityLineItem objLineItem = new OpportunityLineItem();
objLineItem.PriceBookEntryId = objPBEntry.Id;
objLineItem.OpportunityId = objOpporunity.Id;
objLineItem.Quantity = 1;
objLineItem.Unitprice = 500;
Insert objLineItem;