Wednesday, March 21, 2012

Salesforce - Obscure field integrity exception when upserting PricebookEntry

System.DmlException: Upsert failed. First exception on row 0 with id 01uF0000007wq56IAA; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: []

I encountered this exception in an Apex batch job that I inherited (as in I didn't write the original code) and it wasn't really clear what was causing the field integrity exception.

Turns out the code was setting a specific PricebookEntry UnitPrice where the UseStandardPrice was also set to true. When setting a specific UnitPrice the UseStandardPrice should be set to false.

From the help docs:

[Unit price:] "You can specify a value only if UseStandardPrice is set to false."

[UseStandardPrice:] Indicates whether this object uses the standard price defined in the standard Pricebook2 object (true) or not (false). If set to true, then the UnitPrice field is read-only, and the value will be the same as the UnitPricevalue in the corresponding PricebookEntry in the standard price book (that is, the PricebookEntry object whose Pricebook2Id refers to the standard price book and whose Product2Id and CurrencyIsoCode are the same as this object). For PricebookEntry objects associated with the standard Pricebook2 object, this field must be set to true.