Adding Products to Price books using Apex

Apex Apr 14, 2015

Use Case: Assign Price Book for Bulk Products

Are you struggling to assign PriceBook's manually after loading Products in Salesforce? Don't even think of doing it Manually!! Following is a code Snippet that does the trick for you. Please follow the steps listed below:


  • Go to Developer Console
  • Open Execute Ananymous Window, Comman: Ctrl/Cmd + E
  • Paste code below
Set<Id> pbList = new Set<Id>();
for(PricebookEntry pbe : [SELECT Id, UnitPrice, Product2Id, Pricebook2Id, Name, IsActive, ProductCode FROM PricebookEntry]){    

List<PricebookEntry> pbeList = new List<PricebookEntry>();
for(Product2 p: [Select Id, Name FROM Product2 WHERE Id NOT IN : pbList]){
// place you PriceBook2Id below
    pbeList.add(new PricebookEntry(UnitPrice = 10, Pricebook2Id = '01s1a000000WKm9', product2Id = p.Id,isActive = true));

insert pbeList;
  • Place Your PriceBook2Id in line # 10
  • click execute

Sample Screenshot

Thats it!!!

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap