I am trying to create a scheduled batch class to query existing records for a custom object, add it to a list then insert the list of records for the same custom object, then update a custom field for a list belonging to the parent object, via a lookup field . The GF__c
is the child object, and the Opportunity is the parent object. when I run it, it does create the new list of child records, but I am getting an error regarding the parent list:
Duplicate id in List::...
and the custom field of the parent isn't getting updated. I've posted my code below, any assistance is appreciated.
public class GF__cBatch implements Database.Batchable<SObject>, Schedulable {
public GF__cBatch() {}
public void execute(SchedulableContext sc) {
Database.executeBatch(this, 60);
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Opportunity_Name__c, Forecast_Month_Year_Current_Month_Year__c FROM GF__c WHERE Forecast_Month_Year_Current_Month_Year__c=true]);
}
public void execute(Database.BatchableContext bc, List<sObject> scope) {
list<GF__c> gfList = new list<GF__c>();
list<Opportunity> OppList = new list<Opportunity>();
datetime myDateTime = datetime.now();
For(Sobject s :scope){
GF__c GF = (GF__c) s;
gfList.add(new GF__c(
Opportunity_Name__c = GF.Opportunity_Name__c
));
Opplist = [SELECT Id, Forecast_Month_Year__c FROM Opportunity WHERE Id = :GF.Opportunity_Name__c];
OppList.add(new Opportunity(
Id = GF.Opportunity_Name__c,
Forecast_Month_Year__c = myDateTime.format('MMMM, YYYY')
));
}
try{
insert gfList;
if(OppList.size() > 0){
update OppList;
}
}
catch(Exception E){
system.debug('Error is: ' + E.getMessage());
}
}
public void finish(Database.BatchableContext bc) {
system.debug('FORECAST CREATE JOB IS FINISHED');
}
}
{}
button or Ctrl-K) to make sure your code gets rendered appropriately. Thanks!