0

I am trying to insert products, then those products then create price entries if they don't already exist but if they do exist they update the previous price entry based on the name of the product from an import of a csv.

I have already utilised the code below:

             Map<String, Product2> productByName = new Map<String, Product2>();

             for (Product2 prod : [SELECT Name FROM Product2 WHERE Name IN :csvNames]) 
              {
                productByName.put(prod.Name, prod);
              }

              Map<String, PricebookEntry> productByEntry = new Map<String, PricebookEntry>();

              for (PricebookEntry prEntry : [SELECT Name FROM PricebookEntry WHERE Name IN :csvNames]) 
               {
                productByEntry.put(prEntry.Name, prEntry);
               }

            //Section to add in pricebook entries
             for (Integer i = 1; i < csvFileLines.size(); i++) 
                {
                 PricebookEntry prEnt = new PricebookEntry() ;
                 String[] csvRecordData = csvFileLines[i].split(',');
                 String csvName = csvRecordData[0];
                 String unit_price = csvRecordData[5];
                 ID productID = productByName.get(csvRecordData[0]).Id;
                 ID pEntry = productByEntry.get(csvRecordData[0]).Id;
                 ID pricebookID = '01s4J000001yJ9UQAU';

                if(String.isBlank(pEntry) == False)
                 {
                  ID entryId = productByEntry.get(csvRecordData[0]).Id;
                  prEnt.Id = entryId;
                 }

                 prEnt.Product2Id = productID;
                 prEnt.Pricebook2Id = pricebookID;
                 prEnt.IsActive = True;
                 prEnt.UnitPrice = Integer.valueOf(unit_price);
                 prEnt.UseStandardPrice = False;
                 prEnt.CurrencyIsoCode = 'GBP';

                 priceEntry.add(prEnt);
                 
             }

             if(priceEntry.size()>0)
            {
              insert priceEntry;
            }
            
        }

But it appears the productByEntry statement doesn't appear to work as the visualforce page outputs at error once it appears.

What could be there problem here?

1 Answer 1

0

You will have more success with:

for (PricebookEntry prEntry : [SELECT Product2.Name FROM PricebookEntry 
                                WHERE Product2.Name IN :csvNames]) 
           {
            productByEntry.put(prEntry.Product2.Name, prEntry);
           }
0

You must log in to answer this question.

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