-2

i have a requirement that, if i insert new product then the newly created product must associate to all the pricebooks(including std and custom) but i get and error as illegal assignment from list to string i have tried the below code.

String pricebkId= [SELECT id,isStandard from Pricebook2];
List<PricebookEntry> pbeList = new List<PricebookEntry>();
for(Product2 p:  Trigger.New){
    pbeList.add(new PricebookEntry(
                    UnitPrice = 10, 
                    Pricebook2Id = pricebkId, 
                    product2Id = p.Id,
                    isActive = true));
}

insert pbeList;

Thanks

1
  • 1
    Hi Vishal, welcome to SFSE. Please take a moment to scroll through the tour and read How to Ask, then edit your post to include the exact error message verbatim, as well as a specific question (even if it's just "How do I fix this error?").
    – Adrian Larson
    May 26, 2021 at 19:47

1 Answer 1

2

Your query is returning a list of Price Books, not just a single one. So that's why you're getting that error. You'll also need to compensate for that by adding another loop below, so you'll need something like the below:

// Standard Price book must be first
List<PriceBook2> priceBooks = [SELECT Id FROM Pricebook2 ORDER BY IsStandard DESC]; 
List<PricebookEntry> pbeList = new List<PricebookEntry>();
for(Product2 p:  Trigger.New){
    for (PriceBook2 priceBook : priceBooks) {
        pbeList.add(new PricebookEntry(
                        UnitPrice = 10, 
                        Pricebook2Id = priceBook.Id, 
                        product2Id = p.Id,
                        isActive = true));
    }
}

insert pbeList;
8
  • Hi Nicholas thats correct what you said but since i want to avoid inner for loops so how to achieve that?
    – Vishal J
    May 26, 2021 at 19:46
  • @VishalJ You can't, both loops are required.
    – sfdcfox
    May 26, 2021 at 19:53
  • @sfdcfox thanks for the answer but i am getting an error as STANDARD_PRICE_NOT_DEFINED for the product.
    – Vishal J
    May 26, 2021 at 20:02
  • 1
    @VishalJ The first price you specify must use the standard price book. Change your query to: SELECT Id FROM Pricebook2 ORDER BY IsStandard DESC to make sure the standard price book occurs first.
    – sfdcfox
    May 26, 2021 at 20:07
  • @sfdcfox Good callout. I forgot about the ordering. May 26, 2021 at 20:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .