function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
trav2474trav2474 

Clone price book and all the related price book entries...how?

How do i go about cloning a price book and all it's entries? I know you can with the UI...but how do I do it with APEX? I can call the clone method on the pricebook object...but there is nothing like that for the pricebookentry object, that i can find.

 

Thanks in advance.

 

Travis

Best Answer chosen by Admin (Salesforce Developers) 
forecast_is_cloudyforecast_is_cloudy

 

There is indeed a PricebookEntry SObject in Apex - not sure why you didn't find it. In any case, here is the code you'd need to 'deep clone' a Price Book (i.e. clone the related Price Book entries as well):
Pricebook2 p1 = [select id, Name, IsStandard, IsActive, Description from Pricebook2 where id='<specify some Price book id>'];
Pricebook2 p2 = p1.clone(false, true);
insert p2;

PricebookEntry[] pb1 = [Select UseStandardPrice, UnitPrice, ProductCode, Product2Id, Pricebook2Id, Name, IsActive From PricebookEntry where Pricebook2Id = '<specify same Price book id>'];
PricebookEntry[] pb2 = pb1.deepClone(false); for (PricebookEntry x : pb2) { x.Pricebook2Id = p2.Id; } insert pb2;

 

Hope this helps...

 

All Answers

forecast_is_cloudyforecast_is_cloudy

 

There is indeed a PricebookEntry SObject in Apex - not sure why you didn't find it. In any case, here is the code you'd need to 'deep clone' a Price Book (i.e. clone the related Price Book entries as well):
Pricebook2 p1 = [select id, Name, IsStandard, IsActive, Description from Pricebook2 where id='<specify some Price book id>'];
Pricebook2 p2 = p1.clone(false, true);
insert p2;

PricebookEntry[] pb1 = [Select UseStandardPrice, UnitPrice, ProductCode, Product2Id, Pricebook2Id, Name, IsActive From PricebookEntry where Pricebook2Id = '<specify same Price book id>'];
PricebookEntry[] pb2 = pb1.deepClone(false); for (PricebookEntry x : pb2) { x.Pricebook2Id = p2.Id; } insert pb2;

 

Hope this helps...

 

This was selected as the best answer
trav2474trav2474

that worked great...thanks...only change i had to make was to add "IsActive = true" to the pricebookentry query...but other than that it work just like i wanted.

 

Thanks for the help.