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?