This post is a part of the daily blog series
Day #21 – PriceBookEntry Creation with StandardPrice
We have a Product with a standard price of say $100. As shown below, in Salesforce UI, it is easy to add a product and add a standard price (related list). We can also associate the Product to another custom Price Book by clicking on the Add to Price Book button in Price Books related list.
Note here that the custom price book entry has the checkbox “Use Standard Price” ticked which implies that if the standard price is changed for this product, the custom price book entry will also reflect the same. This is a very useful feature.
Now the requirement is that we need to do the same via API as in an Apex class or an Apex trigger automatically. This sounds simple, but there is a catch!
Attempt 1: If you do simple pricebookentry creation like this:
PricebookEntry pbe = new PricebookEntry( Pricebook2Id='xxxxxx', IsActive=true, Product2Id='xxxxxx', UseStandardPrice=true ); insert pbe;
You’d get this error
Error 1: REQUIRED_FIELD_MISSING, Required fields are missing: [UnitPrice]: [UnitPrice]
Attempt 2: Okay, so I add the UnitPrice, but then it gives another error
PricebookEntry pbe = new PricebookEntry( Pricebook2Id='xxxxx', IsActive=true, Product2Id='xxxxx', UseStandardPrice=true, UnitPrice = 0.70 ); insert pbe;
Error 2: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception
Attempt 3: I read that
UseStandardPrice==true cannot be set. It has to be false as per the help document help.salesforce.com/articleView?id=000193277&type=1
PricebookEntry pbe = new PricebookEntry( Pricebook2Id='xxxxx', IsActive=true, Product2Id='xxxxx', UseStandardPrice=false, UnitPrice = 0.70 ); insert pbe;
Result: Setting it to False actually inserts the record. But I want it to be set to true. No error, but not the solution as I want
I have figured out that we cannot set
UseStandardPrice=true on insert. On insert it has to be set to False first, along with mentioning
UnitPrice. Then later do an additional update to set the
PricebookEntry pbe = new PricebookEntry( Pricebook2Id='xxxxx', IsActive=true, Product2Id='xxxxx', UseStandardPrice=false, UnitPrice = 0.70 ); insert pbe; pbe.UseStandardPrice = true; update pbe;
There you go! Perfect. It worked. 2 DMLs though, but it works.
Here’s the full code if you want to do the same in a test class.