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
karthic sankar 9karthic sankar 9 

Need help this method

Hi Experts,

Request you to provide some solution for me.

public class Test_insert {
    public map<String,Integer> EmpMap = new map<String, Integer>();
    public Test_insert(Integer preVetReviews,Integer preVetReviews_Tue,Integer preVetReviews_Wed,Integer preVetReviews_Thur,Integer preVetReviews_Fri)
    {
        Test__c acc= new Test__c();
        EmpMap.put('Monday',preVetReviews);
        EmpMap.put('Tuesday',preVetReviews_Tue);
        EmpMap.put('Wedneday',preVetReviews_Wed);
        EmpMap.put('Thursday',preVetReviews_Thur);
        EmpMap.put('Friday',preVetReviews_Fri);
        set<String> allKeys = EmpMap.keySet();
        list<Integer> allValues = EmpMap.Values();
        for(String k : EmpMap.keySet())
        {
           acc.Name = 'Test';
           acc.PrevetReview__c = EmpMap.get(k);
           System.debug('The Key is: ' +k+ ' and the value is: ' +EmpMap.get(k));
           insert acc;
        }
    }

}

Above is my code and I call it using

Test_insert a = new Test_insert(2,3,4,5,6);

Obseved output:
Record is inserted only once into my object for feild PrevetReview__c

Expected output:
I need record to be inserted five time for feild PrevetReview__c

Please help
Best Answer chosen by karthic sankar 9
Andrew GAndrew G
Try declaring the acc record inside your loop,  By declaring it outside the loop, it is declared once and then the same record is "inserted" many times.  Surprised you are not getting a error message regarding trying to insert rather than update. for example "cannot specify Id in an insert call"

Note also, you should not be doing individual DMLs inside a loop. Its not best practice when  considering bulk update activities.
Example:
      List<Test__c> testList = new List<Test__c>();
      for(String k : EmpMap.keySet())
        {
           Test__c acc= new Test__c();
           acc.Field_1__c = 'Test';
           acc.Field_2__c = EmpMap.get(k);
           System.debug('The Key is: ' +k+ ' and the value is: ' +EmpMap.get(k));
           testList.add(acc);
        }
        insert testList;

regards
Andrew