Adding Products to Price books using Apex

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:

Steps

  • 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]){    
    pbList.add(pbe.Product2Id);
}

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!!!