[SalesForce] new Product2 creating/adding to custom pricebook

I've created small script for inserting new Products2 with Standard Price.

Map<String, Integer[]> newProdMap = new Map<String, List<Integer>>();

newProdMap.put('Product Name', new Integer[]{850, 1000});

Map<String, Product2> prodMap = new Map<String, Product2>();
List<PricebookEntry> pbes = new List<PricebookEntry>();

Pricebook2 pb = [  SELECT id, CurrencyIsoCode
                  FROM Pricebook2
                  WHERE isStandard=true
                  LIMIT 1
               ];

for(String name : newProdMap.keySet()){               
    Product2 p2 = new Product2( Name = name,
                                IsActive = true,
                                CurrencyIsoCode = 'GBP'
                                );
    prodMap.put(name, p2); 
}
insert prodMap.values();   

for(Product2 prod : prodMap.values()){
    for(Integer i = 0; i < 2; i++){
        PricebookEntry pbe = new PricebookEntry(CurrencyIsoCode = i == 0 ? 'GBP' : 'USD' ,
                                                Pricebook2Id = pb.Id,
                                                IsActive = true,
                                                Product2Id = prod.Id,
                                                UnitPrice =  newProdMap.get(prod.Name)[i]
                                                );
        pbes.add(pbe);
    }
}

insert pbes;

As you can see this is pretty easy and work fine.

My question is how I can also add those products to pricebook?
It will be enough just to create separate PriceBookEntries for each Pricebook to which I want add product?

Best Answer

Ok, I am to lazy to wait for answer ;/

It will work, but before adding product to custom PriceBook it must have Standard Price. In other words it must be added to Standard PriceBook.

Related Topic