I'm getting
You have uncommitted work pending. Please commit or rollback before calling out
global class BatchTransactionSurvey implements Database.Batchable<ManualSurveyController.SurveyData>
, DataBase.Stateful
, Database.AllowsCallouts {
private List<ManualSurveyController.SurveyData> data;
private static List<String> results;
global BatchTransactionSurvey(List<ManualSurveyController.SurveyData> data)
{
this.data = data;
results = new List<String>();
}
global Iterable<ManualSurveyController.SurveyData> start(Database.BatchableContext BC)
{
return new TransactionSurveyIterable2(data);
}
global void execute(Database.BatchableContext BC, List<ManualSurveyController.SurveyData> scope)
{
for(ManualSurveyController.SurveyData d : scope)
{
String result;
try{
result = d.acctNum +': '+ TransactionSurveyREST.doPost(d.acctNum, d.activityID, d.processType, d.processSubType, d.rm, d.liaison, d.startDate, d.assetDescription, d.currentCustodian);
}catch(Exception e)
{
result = d.acctNum +': '+ e.getMessage();
}
results.add(result);
}
}
global void finish(Database.BatchableContext BC)
{
CustomEmail.sendBatchResultsEmail(BC.getJobId(), Constants.ADMIN_EMAIL);
CustomEmail.sendSingleHtmlEmail(Constants.ADMIN_EMAIL, Constants.ADMIN_EMAIL, 'Transaction Survey Fix', 'Results', String.join(results, '\r\n') );
}
}
My TransactionSurveyREST class takes the information does some processing and some SOQL statements if everything checks out it does a Callout to Clicktools which returns a URL as a string. The returned string is then used to create a new record
String surveyURL = ClickTools.getSurveyURL(surveyInstance, new List<String>{brandId, activityID, liaison, rm, processType});
Transaction_Survey__c survey = new Transaction_Survey__c(Survey_URL__c = surveyURL);
Database.saveResult sr = Database.insert(survey, false);
String result = '';
if(sr.isSuccess())
{
result = Constants.SUCCESS;
} else
{
for(database.error e: sr.getErrors())
{
result = result + e.getMessage() + Constants.NEW_LINE + Constants.NEW_LINE;
}
}
I've initially set my Batch size to 5 to be well under the 10 Callouts per Batch Execute method. The odd thing is that the DML works for the first record in the Batch, but any subsequent records return the above error. So if I have 10 batches that each process 5 records, only 5 succeed and the rest fail with that error.
What can I do to make this work?