function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris BenoitChris Benoit 

Loop only updates one record

This is my first attempt at apex.  Can anone help me understand why this loop only updates one record when it should be updating multiple?

global class Idea_Votes_Copy_to_Enhancement implements Schedulable{
    global void execute(SchedulableContext ctx) {
        List<SFDC_Component__c> enhList = new List <SFDC_Component__c>();
        SFDC_Component__c ER = new SFDC_Component__c();
        List<Idea> iList=[SELECT VoteTotal, Enhancement_Requirement_ID__c FROM Idea WHERE VoteTotal >0 AND Status !='Deployed' AND Enhancement_Requirement_ID__c != null];
           for(idea i:IList){
            ER.id = i.Enhancement_Requirement_ID__c;
            ER.Vote_Count__c = i.VoteTotal;
            enhList.add(ER);
             }
        Set<SFDC_Component__c> erSet = new Set<SFDC_Component__c>();
        erSet.addAll(enhList);
        enhList.clear();
        enhList.addAll(erSet);  
        upsert enhList; 
    }
}
Salesforce DeveloperSalesforce Developer
Put below line inside the For loop:
SFDC_Component__c ER = new SFDC_Component__c(); 
Just above this line:
ER.id = i.Enhancement_Requirement_id__c;
pankaj kabra 8pankaj kabra 8
As you want to insert multiple records based on number of Ideas fetch from SOQL query you need to initialize it every time inside the for loop else it will be doing the updates on the same record only. Use below code to sort it out.
 
global class Idea_Votes_Copy_to_Enhancement implements Schedulable{
    global void execute(SchedulableContext ctx) {
        List<SFDC_Component__c> enhList = new List <SFDC_Component__c>();
        
        List<Idea> iList=[SELECT VoteTotal, Enhancement_Requirement_ID__c FROM Idea WHERE VoteTotal >0 AND Status !='Deployed' AND Enhancement_Requirement_ID__c != null];
           for(idea i:IList){
		    SFDC_Component__c ER = new SFDC_Component__c();
            ER.id = i.Enhancement_Requirement_ID__c;
            ER.Vote_Count__c = i.VoteTotal;
            enhList.add(ER);
             }
        Set<SFDC_Component__c> erSet = new Set<SFDC_Component__c>();
        erSet.addAll(enhList);
        enhList.clear();
        enhList.addAll(erSet);  
        upsert enhList; 
    }
}