[SalesForce] REQUIRED_FIELD_MISSING & FIELD_INTEGRITY_EXCEPTION on PricebookEntry Insert

I want to use standard price for the Pricebook entry.

  PricebookEntry pbe = new PricebookEntry(Pricebook2Id='01sN00000002OTsIAM',
        IsActive=true, 
        Product2Id='01tN0000004JGeuIAG', 
        UseStandardPrice=true
        );
    insert pbe;

I get this error.

REQUIRED_FIELD_MISSING, Required fields are missing: [UnitPrice]:
[UnitPrice]

So, I changed to mention the List Price (which is the unitPrice). I still get the error!

PricebookEntry pbe = new PricebookEntry(
    Pricebook2Id='01sN00000002OTsIAM',
    IsActive=true, 
    Product2Id='01tN0000004JGeuIAG', 
    UseStandardPrice=true,
    UnitPrice = 0.70
    );

insert pbe;

I get the following error

Insert failed. First exception on row 0; first error:
FIELD_INTEGRITY_EXCEPTION, field integrity exception

UPDATE

I read that UseStandardPrice==true cannot be set. It has to be false. help.salesforce.com/articleView?id=000193277&type=1

Setting it to False actually inserts the record. But I want it to be set to true.

Best Answer

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 UseStandardPrice=true.

PricebookEntry pbe = new PricebookEntry(
    Pricebook2Id='01sN00000002OTsIAM',
    IsActive=true, 
    Product2Id='01tN0000004JGeuIAG', 
    UseStandardPrice=false,
    UnitPrice = 0.70
    );

insert pbe;

pbe.UseStandardPrice = true;
update pbe;